Featured image of post Java设计模式-适配器模式Adapter

Java设计模式-适配器模式Adapter

相关文章

【合集】Java设计模式

应用

对象适配器{@link InputStreamReader}实现Reader,并且组合了实现了Reader的StreamDecoder

原始功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public interface SDCard {
    void readSD();
    void writeSD(String msg);
}
public static class SDCardImpl implements SDCard {
    @Override
    public void readSD() {
        System.out.println("readSD");
    }
    @Override
    public void writeSD(String msg) {
        System.out.println("writeSD");
    }
}

需要适配的功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public interface TFCard {
    void readTF();
    void writeTF(String msg);
}
public static class TFCardImpl implements TFCard {
    @Override
    public void readTF() {
        System.out.println("readTF");
    }
    @Override
    public void writeTF(String msg) {
        System.out.println("writeTF");
    }
}

类适配器

其实就是实现老接口,继承新接口实现类。实现的方法里面调用老接口的方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static class SDAdapterTF extends TFCardImpl implements SDCard {
    @Override
    public void readSD() {
        System.out.println("adapter read tf card ");
    }
    @Override
    public void writeSD(String msg) {
        System.out.println("adapter write tf card");
        writeTF(msg);
    }
}

SDCard sdAdapterTF = new SDAdapterTF();
sdAdapterTF.readSD();

对象适配器

其实就是实现老接口,组合新接口。实现的方法里面调用老接口的方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public static class SDAdapterTF2 implements SDCard {
    private final TFCard tfCard;
    public SDAdapterTF2(TFCard tfCard) {
        this.tfCard = tfCard;
    }

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

SDAdapterTF2 sdAdapterTF2 = new SDAdapterTF2(new TFCardImpl());
sdAdapterTF2.readSD();
皖ICP备2024056275号-1
发表了78篇文章 · 总计149.56k字
本站已稳定运行