7_适配器模式

2021-01-11  本文已影响0人  真是个点子王

结构

类适配者模式

// Computer.java
public class Computer {
    // 从SD卡中读取数据
    public String readSD(SDCard sdCard){
        if(sdCard == null){
            throw new NullPointerException("sd card is not null");
        }
        return sdCard.readSD();
    }
}

// SDCard.java
public interface SDCard {
    // 从SD卡中读取数据
    public String readSD();
    // 往SD卡中写数据
    public void writeSD(String msg);
}

// SDCardImpl.java
public class SDCardImpl implements SDCard {
    @Override
    public String readSD() {
        String msg = "SDCard read msg : hello world SD";
        return msg;
    }

    @Override
    public void writeSD(String msg) {
        System.out.println("SDCard write msg : " + msg);
    }
}

// TFCard.java
public interface TFCard {
    // 从TF卡中读取数据
    public String readTF();

    // 往TF卡中写入数据
    void writeTF(String msg);
}

// TFCardImpl.java
public class TFCardImpl implements TFCard{
    @Override
    public String readTF() {
        String msg = "TFCard read msg : hello world TFCard";
        return msg;
    }

    @Override
    public void writeTF(String msg) {
        System.out.println("TFCard write:" + msg);
    }
}

// SDAdapterTF.java
public class SDAdapterTF extends TFCardImpl implements SDCard{
    @Override
    public String readSD() {
        System.out.println("adapter read tf card");
        return readTF();
    }

    @Override
    public void writeSD(String msg) {
        System.out.println("adapter write tf card");
        writeTF(msg);
    }
}

// Client.java
public class Client {
    public static void main(String[] args) {
        // 创建计算机对象
        Computer computer = new Computer();

        String msg = computer.readSD(new SDCardImpl());

        System.out.println(msg);

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

        // 使用该计算机读取TF卡中的数据卡
        String msg1 = computer.readSD(new SDAdapterTF());
        System.out.println(msg1);
    }
}

对象适配器模式

// SDAdapterTF.java
public class SDAdapterTF extends SDCardImpl {

    // 声明适配者类
    private TFCard tfCard;

    public SDAdapterTF(TFCard tfCard){
        this.tfCard = tfCard;
    }

    @Override
    public String readSD() {
        System.out.println("adapter read tf card");
        return tfCard.readTF();
    }

    @Override
    public void writeSD(String msg) {
        System.out.println("adapter write tf card");
        tfCard.writeTF(msg);

 // Client.java
public class Client {
    public static void main(String[] args) {
        // 创建计算机对象
        Computer computer = new Computer();

        String msg = computer.readSD(new SDCardImpl());

        System.out.println(msg);

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

        // 读取TF卡中的数据
        String msg1 = computer.readSD(new SDAdapterTF(new TFCardImpl()));
        System.out.println(msg1);
    }
}
上一篇下一篇

猜你喜欢

热点阅读