适配器模式

适配器模式:Retrofit中使用到。

什么样的类型就通过什么样的适配器适配
在CallAdapter和Converter中用到,
如果我需要得到一个Weather对象,则对应的WeatherConverter去调用,如果需要String,则StringConverter调用

public class MyConverter extends Converter.Factory {
    @Nullable
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        LogUtil.Companion.d("yocn MyConverter type->" + type);
        if (type == String.class) {
            return new StringConverter();
        } else if (type == Weather.class) {
            return new WeatherConverter();
        }
        return super.responseBodyConverter(type, annotations, retrofit);
    }

    class StringConverter implements Converter<ResponseBody, String> {

        @Nullable
        @Override
        public String convert(ResponseBody value) throws IOException {
            return value.string();
        }
    }

    class WeatherConverter implements Converter<ResponseBody, Weather> {

        @Nullable
        @Override
        public Weather convert(ResponseBody value) throws IOException {
            Weather weather = new Weather();
            weather.setCount(100);
            weather.setStatus(999);
            weather.setInfo("I'm A Fake Weather create by MyConverter!");
            Exception e = new Exception("this is a exception log for print");
            e.printStackTrace();
            return weather;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容