Java基础Android

[设计模式]适配器模式

2020-03-16  本文已影响0人  Merbng

定义

例子

就拿日本电饭煲的例子进行说明,日本电饭煲接口标准是110v电压,而中国标准电压接口是220v,所以想要在中国用日本电饭煲,就需要一个电源转换器


/**日本11v 电源接口
 * Created by merbng on 2020/3/14.
 */

public interface JP110VInterface {
      void connect();
}


/**
 * 日本110v 电源
 * Created by merbng on 2020/3/14.
 */

public class JP110VInterfaceImpl implements JP110VInterface {
    @Override
    public void connect() {
        Log.e("", "日本110V电源开始工作...");
    }
}


/**中国220v 电源接口
 * Created by merbng on 2020/3/14.
 */

public interface China220VInterface {
    public void connect();
}

/**
 * 中国220v 电源
 * Created by merbng on 2020/3/14.
 */

public class China220VInterfaceImpl implements China220VInterface {
    @Override
    public void connect() {
        Log.e("==设计模式:适配器模式==", "中国220V电源开始工作...");
    }
}


/**
 * 电饭煲
 * Created by merbng on 2020/3/14.
 */

public class ElectricCooker {
    private JP110VInterface jp110VInterface;

    public ElectricCooker(JP110VInterface jp110VInterface) {
        this.jp110VInterface = jp110VInterface;
    }

    public void work() {
        jp110VInterface.connect();
        Log.e("==设计模式:适配器模式==","电饭煲开始工作...");
    }
}



/**
 * Created by merbng on 2020/3/14.
 */

public class PowerAdapter implements JP110VInterface {
    China220VInterface china220VInterface;

    public PowerAdapter(China220VInterface china220VInterface) {
        this.china220VInterface = china220VInterface;
    }

    @Override
    public void connect() {
        china220VInterface.connect();
    }
}



public class AdapterModeTest extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        China220VInterface china220VInterface = new China220VInterfaceImpl();
        PowerAdapter adapter = new PowerAdapter(china220VInterface);
        ElectricCooker electricCooker = new ElectricCooker(adapter);
        electricCooker.work();
    }
}

总结

主要优点:

缺点:
过多的使用适配器会让系统显得过于凌乱,如果不是很远必要,可以不使用适配器而是直接对系统进行重构

参考链接:

上一篇 下一篇

猜你喜欢

热点阅读