[设计模式]适配器模式
[设计模式]适配器模式
Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
-
类适配器
//接口转换器的抽象实现 public interface NetToUSB { public void handleRequest(); }//网线类 public class NetWire { public void request(){ System.out.println("连接网线上网!"); } }//适配器类 public class Adapter extends NetWire implements NetToUSB{ @Override public void handleRequest() { super.request(); } }//电脑类和测试方法 public class Computer { public void net(NetToUSB adapter){ //上网 adapter.handleRequest(); } public static void main(String[] args) { Computer computer = new Computer(); NetWire netWire = new NetWire(); Adapter adapter = new Adapter(); computer.net(adapter); } }缺点:
- 对于Java、C#等不支持多重类继承的语言,一次最多只能适配一个适配者类。
- 在Java、C#等语言中,类适配器模式中的目标抽象类只能为接口,不能为类,其使用有一定的局限性。
-
对象适配器
//接口转换器的抽象实现 public interface NetToUSB { public void handleRequest(); }//网线类 public class NetWire { public void request(){ System.out.println("连接网线上网!"); } }//适配器类 public class Adapter implements NetToUSB{ private NetWire netWire; public Adapter(NetWire netWire) { this.netWire = netWire; } @Override public void handleRequest() { netWire.request(); } }//电脑类和测试方法 public class Computer { public void net(NetToUSB adapter){ //上网 adapter.handleRequest(); } public static void main(String[] args) { Computer computer = new Computer(); NetWire netWire = new NetWire(); Adapter adapter = new Adapter(netWire); computer.net(adapter); } }优点:
- 一个对象适配器可以把多个不同的适配者适配到同一个目标。
- 可以适配一个适配者的子类。

浙公网安备 33010602011771号