Convert转换模式

2018-02-05  本文已影响0人  石器时代小古董
1.数据类型进行转换时,如果客户端不需要了解转换的细节,可以用转换器作为中间件。
2.当你可能需要转换成不同数据而不期望改动实现逻辑。可以通过传递不同的转换器实现。
3.从数据库中获得数据转换成对应的Bean.

参考Retrofit的转换接口

public interface Converter<F, T> {
 //转换接口
  T convert(F value) throws IOException;
  //指定生成转换器接口
  abstract class Factory {
    
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }

    public Converter<?, RequestBody> requestBodyConverter(Type type,
        Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
      return null;
    }

    public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }
  }
}

默认转换类

image.png

扩展的转换类

image.png

客户端使用

可以看到,他们都将传入的位置类型的数据转换成一个RequestBody类型供客户端使用。而客户端并不知道具体的转换细节。

    /**
     * Builds a method return value from an HTTP response body.
     */
    T toResponse(ResponseBody body) throws IOException {
        return responseConverter.convert(body);
    }

如果客户端需要替换一个生成RequestBody的方式,只需要在替换一下实现的方式


image.png
上一篇 下一篇

猜你喜欢

热点阅读