设计模式--适配器模式

来源:互联网 发布:美图还原软件 编辑:程序博客网 时间:2024/06/05 11:36

一、转载说明

本博文转自下文,实操,亲测
http://blog.csdn.net/suifeng3051/article/details/51497041

二、模式详解

现有 220V中国标准电源、220V中国标准电饭煲 110V日本标准电源、110V日本标准电饭煲需要110V日本标准电饭煲使用中国220V标准电源工作 那么需要一个电源适配器才能满足该条件

2.1两种电源

2.1.1中国220V标准电源接口及实现

package cn.edu.sdut.softlab.powerinterface;/** * 中国220V电源接口 *  */public interface CN220VInterface {    public void connect();}
package cn.edu.sdut.softlab.powerinterface;/** * 中国220V电源接口实现 *  */public class CN220VInterfaceImpl implements CN220VInterface {    @Override    public void connect() {        System.out.println("接通电源,开始工作!");    }}

2.1.2日本110V标准电源接口及实现

package cn.edu.sdut.softlab.powerinterface;/** * 日本110V电源接口 *  */public interface JP110VInterface {    public void connect();}
package cn.edu.sdut.softlab.powerinterface;/** * 日本110V接口实现 * */public class JP110VInterfaceImpl implements JP110VInterface {    @Override    public void connect() {        System.out.println("接通电源,开始工作!");    }}

2.2两种电饭煲

2.3适配器

2.3.1电源适配器

package cn.edu.sdut.softlab.poweradaptor;import cn.edu.sdut.softlab.powerinterface.CN220VInterface;import cn.edu.sdut.softlab.powerinterface.JP110VInterface;/** * 电源适配器 继承JP110VInterface,用220VInterface进行适配 实现JP110VInterface的方法 *  */public class PowerAdaptor implements JP110VInterface {    private CN220VInterface cn220VInterface;    public PowerAdaptor(CN220VInterface cn220VInterface) {//注意:该构造器需要设置为public类型的        this.cn220VInterface = cn220VInterface;    }    @Override    public void connect() {        cn220VInterface.connect();    }}

2.4日本电饭煲使用中国电源工作

2.4.1实例化一个日本电饭煲

package cn.edu.sdut.softlab.cooker;

import cn.edu.sdut.softlab.powerinterface.JP110VInterface;/** * 使用一个110V电饭煲,使用110V电源做饭 *  */public class JP110VElectricCooker {    private JP110VInterface jp110VInterface;    JP110VElectricCooker(JP110VInterface jp110VInterface) {        this.jp110VInterface = jp110VInterface;    }    // 做饭    public void cook() {        jp110VInterface.connect();// 接通电源        System.out.println("开始做饭!");    }}

2.4.2使用电源适配器满足工作条件

package cn.edu.sdut.softlab.cooker;import cn.edu.sdut.softlab.poweradaptor.PowerAdaptor;import cn.edu.sdut.softlab.powerinterface.CN220VInterface;import cn.edu.sdut.softlab.powerinterface.CN220VInterfaceImpl;/** * 适配器开始工作 使用中国的220V电源 利用适配器 使用日本的110V的电饭煲工作 */public class AdaptorWork {    public static void main(String[] args) {        // 使用中国的220V电源        CN220VInterface cn220VInterface = new CN220VInterfaceImpl();        // 使用电源适配器        PowerAdaptor powerAdaptor = new PowerAdaptor(cn220VInterface);        // 使用日本110V电源的电饭煲        JP110VElectricCooker cooker = new JP110VElectricCooker(powerAdaptor);        // 开始工作        cooker.cook();    }}

三、源码分享

https://github.com/GaoZiqiang/AdaptorTest

0 0