1、定义
将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类的可以一起工作。
2、角色分析
3、类图分析
4、优缺点分析
(1)对象适配器优点
(2)类适配器缺点
5、适用场景
6、代码实例
需要适配的类:
1 /** 2 * @author it-小林 3 * @desc 要被适配的类:网线 4 * @date 2021年07月20日 19:59 5 */ 6 public class Adaptee { 7 8 public void request(){ 9 System.out.println("连接网线上网"); 10 } 11 }
目标接口
1 /** 2 * @author it-小林 3 * @desc 接口转换器的抽象实现 4 * @date 2021年07月20日 20:01 5 */ 6 public interface NetToUsb { 7 8 /** 9 * 10 * 作用:处理请求,网线=》usb 11 */ 12 public void handleRequest(); 13 }
类适配器
1 //1.继承(类适配器,单继承) 2 /** 3 * @author it-小林 4 * @desc 真正的适配器~ 需要链接usb, 链接网线 5 * @date 2021年07月20日 20:03 6 */ 7 public class Adapter extends Adaptee implements NetToUsb { 8 @Override 9 public void handleRequest() { 10 super.request(); 11 } 12 }
对象适配器
//2.组合(对象适配器:常用) /** * @author it-小林 * @desc 真正的适配器~ 需要链接usb, 链接网线 * @date 2021年07月20日 20:03 */ public class Adapter2 implements NetToUsb { private Adaptee adaptee; public Adapter2(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void handleRequest() { adaptee.request(); } }
1 /** 2 * @author it小林 3 * @desc 客户端类:想上网,插不上网线 4 * @date 2021年07月20日 20:00 5 */ 6 public class Computer { 7 //需要链接转接器才可以上网 8 public void net(NetToUsb adapter) { 9 //上网的具体实现,找一个转接头 10 adapter.handleRequest(); 11 } 12 13 public static void main(String[] args) { 14 //电脑 适配器 网线 15 /*Computer computer = new Computer(); //电脑 16 Adaptee adaptee = new Adaptee();//网线 17 Adapter adapter = new Adapter(); //转接器 18 19 computer.net(adapter);*/ 20 21 Computer computer = new Computer(); //电脑 22 Adaptee adaptee = new Adaptee();//网线 23 Adapter2 adapter = new Adapter2(adaptee); //转接器 24 computer.net(adapter); 25 } 26 }
原文:https://www.cnblogs.com/linruitao/p/15036702.html