设计模式适配器模式
本文最后更新于:2024年3月18日 凌晨
设计模式适配器模式
- 适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
- 这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。举个真实的例子,读卡器是作为内存卡和笔记本之间的适配器。您将内存卡插入读卡器,再将读卡器插入笔记本,这样就可以通过笔记本来读取内存卡。
类适配器模式
- 类适配器模式需要多重继承对一个接口对另一个接口进行适配,而C#,Java不支持多重继承,其使用有一定的局限性(不推荐使用)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| interface Adapter { void handleRequest(); }
class NetworkAdapter extends NetworkCable implements Adapter { @Override public void handleRequest() { super.connectDevice(); } }
class NetworkCable { void connectDevice() { System.out.println("成功连接设备"); } }
class Device { public void connectNetwork(Adapter adapter) { adapter.handleRequest(); } }
public class AdapterMode { public static void main(String[] args) { Device device = new Device(); Adapter adapter = new NetworkAdapter(); device.connectNetwork(adapter); } }
|
对象适配器模式
- 采用组合的方式,一个对象适配器可以把多个不同的适配者适配到同一个目标。
- 可以适配一个适配者的子类,由于适配器和适配者之间是关联关系,根据"里氏代换原则",适配者的子类也可以通过该适配器进行适配。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| interface Adapter { void handleRequest(); }
class NetworkAdapter implements Adapter {
private NetworkCable networkCable;
public NetworkAdapter(NetworkCable networkCable) { this.networkCable = networkCable; }
@Override public void handleRequest() { networkCable.connectDevice(); } }
class NetworkCable { void connectDevice() { System.out.println("成功连接设备"); } }
class Device { public void connectNetwork(Adapter adapter) { adapter.handleRequest(); } }
public class AdapterMode { public static void main(String[] args) { Device device = new Device(); Adapter adapter = new NetworkAdapter(new NetworkCable()); device.connectNetwork(adapter); } }
|