【Retrofit】Retrofit原理解析之设计模式总结篇

本文深入探讨了Retrofit框架的设计模式应用,包括代理模式、建造者模式和策略模式等,并详细解析了每种模式在Retrofit中的实现方式及作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学而不思则罔,思而不学则殆


Retrofit系列文章

【Retrofit】Retrofit原理解析之使用篇
【Retrofit】Retrofit原理解析之原理篇
【Retrofit】Retrofit原理解析之注解详解篇
【Retrofit】Retrofit原理解析之设计模式总结篇

设计模式总结

代理模式

动态代理

没啥好说的,这个Retrofit的核心。

  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);
              }
            });
  }

静态代理

针对Call<?>:
在这里插入图片描述
ExecutorCallbackCall相当于代理类,代理真正的对象OkHttpCall.

建造者模式

常见的Builder模式
在这里插入图片描述

策略模式

策略模式(Strategy Pattern):定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换,策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。策略模式是一种对象行为型模式。

CallAdapter

在这里插入图片描述

Converter

public interface Converter<F, T> {
  @Nullable
  T convert(F value) throws IOException;
  
}

在这里插入图片描述

ParameterHandler

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值