适配器模式

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

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

public class MyConverter extends Converter.Factory {
    @Nullable
    @Override
    public Converter 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 {

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

    class WeatherConverter implements Converter {

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

你可能感兴趣的:(适配器模式)