设计模式 by Java——适配器模式

2022-07-31,,,

一个简单的例子,模拟电脑插入电源插座。假设中国电脑额定电压为220V,美国电脑额定电压为110V,中国家用交流电电压220V。

1.不使用适配器的情况

电源插座类

public class Socket {
    private final int VOLTAGE = 220;

    public int getVOLTAGE() {
        return this.VOLTAGE;
    }
}

电脑类

public abstract class Computer {

    public void insert(Socket socket) {
        System.out.println(getName() + "已插入电源插座");
        if (socket.getVOLTAGE() == this.getVoltage()) {
            System.out.println("电源电压合适,工作正常");
        } else {
            System.out.println("电源电压不合适,将要爆炸");
        }
    }

    abstract int getVoltage();

    abstract String getName();
}

中国电脑类,继承电脑类

public class ComputerCN extends Computer {

    @Override
    int getVoltage() {
        return 220;
    }

    @Override
    String getName() {
        return "中国电脑";
    }
}

美国电脑类,继承电脑类

public class ComputerUS extends Computer {

    @Override
    int getVoltage() {
        return 110;
    }

    @Override
    String getName() {
        return "美国电脑";
    }
}

客户端类,测试一下结果

public class AdapterPatternTest {
    public static void main(String[] args) {
        Computer computer0 = new ComputerCN();
        Socket socket0 = new Socket();
        computer0.insert(socket0);

        System.out.println("-----");

        Computer computer1 = new ComputerUS();
        Socket socket1 = new Socket();
        computer1.insert(socket1);
    }
}

运行结果

中国电脑已插入电源插座
电源电压合适,工作正常
-----
美国电脑已插入电源插座
电源电压不合适,将要爆炸

Process finished with exit code 0

2.添加适配器

美国电脑电源适配器类,继承电源插座类

public class AdapterUS extends Socket {
    private final int VOLTAGE = 110;

    @Override
    public int getVOLTAGE() {
        return this.VOLTAGE;
    }
}

客户端类,只需要修改一个地方(Socket的实例化)

public class AdapterPatternTest {
    public static void main(String[] args) {
        Computer computer0 = new ComputerCN();
        Socket socket0 = new Socket();
        computer0.insert(socket0);

        System.out.println("-----");

        Computer computer1 = new ComputerUS();
        Socket socket1 = new AdapterUS();
        computer1.insert(socket1);
    }
}

运行结果

中国电脑已插入电源插座
电源电压合适,工作正常
-----
美国电脑已插入电源插座
电源电压合适,工作正常

Process finished with exit code 0

本文地址:https://blog.csdn.net/qq_24671941/article/details/107687541

《设计模式 by Java——适配器模式.doc》

下载本文的Word格式文档,以方便收藏与打印。