转载

Java设计模式——适配器模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingyunxiaohai/article/details/91358243

适配器模式是将一个类的接口转换成开发者希望的另一个接口

下面参考Retrofit的源码学习适配器模式,Retrofit现在的Andorid开发者基本都用到过,里面用到了很多设计模式比如动态代理模式,适配器模式等。下面来看其中的一个适配器

在使用Retrofit的时候我们经常会看到下面的写法来添加一个addCallAdapterFactory,如果我们不添加,会有自己的一个CallAdapter返回一个Call对象,如果我们想和RxJava结合使用只需要添加一个RxJava的CallAdapter即可。

Retrofit retrofit = new Retrofit.Builder()
         .baseUrl("")
         .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
         .build();
//  Retrofit的create方法源码       
public <T> T create(final Class<T> service) {
   ......
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          private final Platform platform = Platform.get();

          @Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
              throws Throwable {
        ......
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.adapt(okHttpCall);
          }
        });
  }

下面开始仿照Retrofit写一下适配器模式

首先有一个Call接口和CallAdapter适配器和一个Call的实现类OkHttpCall,CallAdapter中有一个抽象工厂类里面有个get()方法可以返回自己。

public interface Call<T> {
    void enqueue();
}

public interface CallAdapter<R,T> {

    T adapt(Call<R> call);

    abstract class Factory{
       public abstract CallAdapter<?,?> get();
    }
}
public class OkHttpCall<T> implements Call<T> {
    @Override
    public void enqueue() {
      //请求网络
    }
}

实现一个默认的 CallAdapter

public class ExecutorCallAdapterFactory extends CallAdapter.Factory {
    @Override
    public CallAdapter<?, ?> get() {
        return new CallAdapter<Object, Call<?>>() {
            @Override
            public Call<?> adapt(Call<Object> call) {
                System.out.println("default 方式");
                return new ExectorCallbackCall<>();
            }
        };
    }
    static final class ExectorCallbackCall<T> implements Call<T>{

        @Override
        public void enqueue() {

        }
    }
}

在实现一个RxJava的CallAdapter

public class RxJavaCallAdapterFactory extends CallAdapter.Factory {
    @Override
    public CallAdapter<?, ?> get() {
        return new CallAdapter<Object, Observable<?>>() {
            @Override
            public  Observable<?> adapt(Call<Object> call) {
                System.out.println("rxjava 方式");
                ObservableOnSubscribe subscribe = new ObservableOnSubscribe() {
                    @Override
                    public void subscribe(ObservableEmitter emitter) throws Exception {

                    }
                };
                return Observable.create(subscribe);
            }
        };
    }
}

Retrofit类中调用

public class Retrofit {

    private CallAdapter.Factory mFactory;

    private Retrofit(CallAdapter.Factory factory) {
        mFactory = factory;
    }

    public CallAdapter callAdapter(){
        return mFactory.get();
    }

    public <T> T create(){
      ServiceMethod serviceMethod = new ServiceMethod.Builder<>(this).build();
      OkHttpCall okHttpCall = new OkHttpCall();
      return (T) serviceMethod.adapt(okHttpCall);
    }

    public static final class Builder{
        CallAdapter.Factory mFactory;
        public Builder addCallAdapterFactory(CallAdapter.Factory factory){
            mFactory = factory;
            return this;
        }
        public Retrofit build(){
            if(mFactory == null){
                return new Retrofit(new ExecutorCallAdapterFactory());
            }
            return new Retrofit(mFactory);
        }
    }
}

通过ServiceMethod把Retrofit和CallAdapter连起来

public class ServiceMethod<R,T> {

    private CallAdapter<R,T> mCallAdapter;

    private <R, T> ServiceMethod(Builder builder) {
       mCallAdapter = builder.mCallAdapter;
    }

    T adapt(Call<R> call){
        return mCallAdapter.adapt(call);
    };

    static final class Builder<R,T>{
        Retrofit mRetrofit;
        CallAdapter<R,T> mCallAdapter;

        public Builder(Retrofit retrofit) {
            mRetrofit = retrofit;
        }
        public ServiceMethod build(){
            mCallAdapter = createCallAdapter();
            return new ServiceMethod(this);
        }

        private CallAdapter<R, T> createCallAdapter() {
            return mRetrofit.callAdapter();
        }
    }
}

最后调用:

Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(new RxJavaCallAdapterFactory())
                .build();
  retrofit.create();

如果不加addCallAdapterFactory运行输出:“default 方式”

如果添加了运行输出:“rxjava 方式”

适配器模式完成。

原文  https://blog.csdn.net/mingyunxiaohai/article/details/91358243
正文到此结束
Loading...