设计模式(8)—— 结构型 ——适配器(Adapter)

版权声明:如有任何疑问,欢迎@我:[email protected] https://blog.csdn.net/qq_37206105/article/details/84147752
  • 定义:将一个类的接口转换成客户期望的另一个接口,使原本接口不兼容的类可以一起工作
  • 类型:结构型
  • 适用场景:
    • 已经存在的类,它的方法和需求不匹配时(方法结果系统或者相似)
    • 不是软件设计阶段考虑的设计模式,是随着软件维护,由于不同产品,不同厂家造成功能类似而接口不相同情况下的解决方案。
  • 优点:
    • 提高类的透明性和复用,现有的类复用但不需要改变
    • 目标类和适配器解耦,提高程序的扩展性
    • 符合开闭原则
  • 缺点
    • 适配器编写过程需要全面考虑,可能会增加系统的复杂性
    • 增加系统代码可读的难度
  • 扩展
    • 对象适配器
    • 类适配器
  • 相关的设计模式
    • 适配器和外观模式

代码实现

借鉴它人博客

另外,引入生活中的例子。下面也是借鉴他人(@geely)代码,例子非常好:

/**
 * Created by geely
 * 民用电源220V
 */
public class AC220 {
    public int outputAC220V(){
        int output = 220;
        System.out.println("输出交流电"+output+"V");
        return output;
    }
}
/**
 * Created by geely
 * 充电器,电源适配器。
 */
public class PowerAdapter implements DC5{
    private AC220 ac220 = new AC220();

    @Override
    public int outputDC5V() {
        int adapterInput = ac220.outputAC220V();
        //变压器...
        int adapterOutput = adapterInput/44;

        System.out.println("使用PowerAdapter输入AC:"+adapterInput+"V"+"输出DC:"+adapterOutput+"V");
        return adapterOutput;
    }
}

适配器接口

/**
 * Created by geely
 */
public interface DC5 {
    int outputDC5V();
}

测试代码类Test

/**
 * Created by geely
 */
public class Test {
    public static void main(String[] args) {
        Target target = new ConcreteTarget();
        target.request();

        Target adapterTarget = new Adapter();
        adapterTarget.request();



    }
}

猜你喜欢

转载自blog.csdn.net/qq_37206105/article/details/84147752