美文网首页
适配器模式

适配器模式

作者: YocnZhao | 来源:发表于2019-02-15 17:10 被阅读0次

    适配器模式: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;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:适配器模式

          本文链接:https://www.haomeiwen.com/subject/egsmeqtx.html