设计模式学习小结

设计模式小结-适配器模式

2017-10-06  本文已影响44人  r09er

适配器模式概述

笔记本电脑的工作电压是20V,而我国的家庭用电是220V,如何让20V的笔记本电脑能够在220V的电压下工作?答案是引入一个电源适配器(AC Adapter),俗称充电器或变压器,有了这个电源适配器,生活用电和笔记本电脑即可兼容,引入一个电源适配器一样引入一个称之为适配器的角色来协调这些存在不兼容的结构,这种设计方案即为适配器模式。

适配器模式优缺点

优点

缺点

三种适配器模式

由于Java不支持多继承,所以运用较少

持有需要适配的目标对象,较为常用

JDK中的WindowAdapter

示例

电脑的电源适配器和插座,使用适配器模式实现。

示例代码

//电脑类,设配目标(Target)
public  class Computer{

    public void connectWith20V(){
        System.out.println("20V充电");
    }
}
//插座,国内插座220V
public interface Socket {
    void supplyWith220V();
}
//类适配器模式
public class ChargerAdapter  extends Computer implements Socket {

    @Override
    public void supplyWith220V() {
        System.out.println("连接220V插座");
        super.connectWith20V();
    }
}
//对象适配器模式
public class Charger2Adapter implements Socket{
    private Computer computer;
    public Charger2Adapter(Computer computer) {
        this.computer = computer;
    }

    @Override
    public void supplyWith220V() {
        System.out.println("连接220V插座");
        computer.connectWith20V();
    }
}
//接口适配器(缺省适配器)
public class Charger3Adapter extends ComputerAdapter {

    private Computer computer;
    
    @Override
    public void supplyWith220V() {
        super.supplyWith220V();
    }

    public void connectWith20V() {
        this.supplyWith220V();
        computer.connectWith20V();
    }

    public void setComputer(Computer computer) {
        this.computer = computer;
    }
}
//调用
 public static void main(String[] args) {
//类适配器
//Socket socket = new ChargerAdapter();
//socket.supplyWith220V();

//对象适配器
//Computer computer = new Computer();
//Socket socket2 = new Charger2Adapter(computer);
//socket2.supplyWith220V();


//接口适配器(缺省适配器)
//Computer computer = new Computer();
//Charger3Adapter charger3Adapter = new Charger3Adapter();
//charger3Adapter.setComputer(computer);
//charger3Adapter.connectWith20V();


}
上一篇 下一篇

猜你喜欢

热点阅读