5

I think Retrofit uses Facade design pattern

  • Is it true, If so how does it use it ( Since Facade gives a common interface to set of subsystems - Thus client can interact with this interface )
  • Does retrofit uses any other design pattern, if so how does it use it
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • @Zun ... This is a valid question as per guidelines. – Devrath Aug 02 '19 at 08:41
  • I consider it low quality because you can simply look at the source code. I don't see the purpose in asking. But hey different opinions and I respect that. I mean, looking at their class names you can even see what patterns they use (Adapter, Factory, Builder, Observers etc. https://github.com/square/retrofit/tree/master/retrofit/src/main/java/retrofit2), since it creates an abstraction you know it's a facade. it uses interceptor through OkHTTP. All of this can be found simply by reading their site – Zun Aug 02 '19 at 08:42

2 Answers2

9

Retrofit uses about 12 design patterns :

1- Builder Pattern: to separate the construction of a complex object from its representation.

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();

2- Façade Pattern: Facade mode requires that the external and internal communication of a subsystem must be carried out through a unified object, and this unified object in retrofit is the Retrofit object we created. We only configure Retrofit, and then obtain the interface object request data, the rest are Retrofit Things inside the framework, we don’t need to care.

interface BooksApi {
    @GET("books")
    fun listBooks(): Call<List<Book>>
}

3- Proxy Pattern: is used in the create method to create the interface object, as follows

public <T> T create(final Class<T> service) {
validateServiceInterface(service);
return (T)
    Proxy.newProxyInstance(
        service.getClassLoader(),
        new Class<?>[] {service},
        new InvocationHandler() {
          private final Platform platform = Platform.get();
          private final Object[] emptyArgs = new Object[0];

          @Override
          public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args)
              throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            args = args != null ? args : emptyArgs;
            return platform.isDefaultMethod(method)
                ? platform.invokeDefaultMethod(method, service, proxy, args)
                : loadServiceMethod(method).invoke(args);
          }
        });
}

4- Adapter Pattern: is used by CallAdapter to transform the interface of one class into another interface that the client expects.

5- Abstract Factory Pattern: CallAdapter.Factory is an abstract factory, CallAdapter is the product interface of the factory.

Retrofit.Builder()
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()

6- Factory Pattern: The CallAdapter interface is also this interface, and its adapt method is this method of creating objects. For example, the adapt method of RxJava2CallAdapter will create an RxJava event stream object, and the anonymous inner class CallAdapter under ExecutorCallAdapterFactory will create an ExecutorCallbackCall object.

7- Decorator Pattern: ExecutorCallbackCall uses this mode in retrofit. For example, ExecutorCallbackCall enhances the function of OkHttpCall. The enqueue method mode of OkHttpCall is asynchronous. When the child thread is called, the return will be in the child thread. Switch to the main thread. It withProxy modevery similar.

8- Strategy Pattern: Retrofit addCallAdapterFactory() with addConverterFactory() Used to configure policies. In addCallAdapterFactory() Taking an example, the configured interface adaptation plant object is the policy context Context, CallAdapter Corresponding to strategy abstraction, different interface adapters are implemented CallAdapter.adapt() Methods, different factories will produce different strategies to achieve classes, and different strategies implemented ADAPT () behavior.

9- Observer Pattern: RXJAVA supported by Retrofit uses the observer mode, not only that, call the OkhttpCall object enqueue() When the method, the callback is used. The callback is also an observer mode.

10- Prototype Pattern: It is mainly used to copy an object. Creating an object using prototype mode is much better than direct New an object, because Object's Clone () is a local method, you can directly operate memory. Another benefit of prototype mode is to simplify object creation, if you need to create an object multiple times in a piece of code, you may wish to use prototype mode. Prototype mode usually needs to be realized Cloneable interface Indicates that the object is copied.

11- Flyweight Pattern: to reuse existing similar objects, if matching objects are not found, create new objects to reduce the number of creating objects to reduce memory, and improve performance. This type of design pattern belongs to structure mode.

12- Singleton Pattern: to ensure that there is only the unique objects of such classes in memory, belonging to the creation mode.

Check this article and this for more details.

Islam Ahmed
  • 668
  • 9
  • 19
1

This is by no means a comprehensive answer, but too long for a comment.

I wouldn't say it has a single pattern. You can definitely find several there, i.e., Builder for when you are building the retrofit instance.

I guess one could say the main pattern is the Proxy Pattern. To the best of my knowledge Retrofit uses this to implement the api interface we define.

It creates a proxy object for the interface and every time the methods get called, it will go through the annotations and build the correct http request. From our perspective it feels like we're calling an implementation, but it's actually a proxy.

I suppose one could say that for the interceptors it uses Chain of Responsibility. However, the interceptors are part of a dependency - OkHttp - rather than retrofit itself.

As for the question "How does it use it in Android?" - I'd say no different than in any other place. Retrofit's design patterns are not specific for Android and would work everywhere the same.

Fred
  • 16,367
  • 6
  • 50
  • 65