关于Adapter( 适配器)模式
Adapter的定义:将一个类的接口转换为客户端所期待的另一接口。Adpater能够让各个类之间相互协作,而不受不兼容接口的影响。
Adapter分为对象Adapter和类Adapter两种。
对象Adapter:
1 interface USBPort{ //定义USB接口 2 void workWithUSB(); 3 } 4 interface PS2Port{ //定义PS2接口 5 void workWithPS2(); 6 } 7 class PS2Mouse implements PS2Port{ //定义PS2接口鼠标实现PS2Port 8 public void workWithPS2(){ 9 System.out.println("使用PS2接口连接工作"); 10 } 11 } 12 class PS2ToUSB implements USBPort{ 13 private PS2Port ps2Port=null; //存放一个PS2Port的对象引用 14 public PS2ToUSB(PS2Port ps2Port){ 15 this.ps2Port=ps2Port; 16 } 17 public void workWithUSB(){ 18 ps2Port.workWithPS2(); //调用PS2Port对象的workWithPS2()方法 19 } 20 } 21 class Computer{ //定义一个Computer,没有PS2插孔,只能连USB鼠标 22 23 public void connectMouse(USBPort usb){ //连接USB鼠标 24 usb.workWithUSB(); 25 } 26 } 27 public class AdapterDemo{ 28 public static void main(String args[]){ 29 30 Computer computer=new Computer(); //声明一个电脑对象,但是电脑正常使用只能接受USB接口的鼠标 31 PS2Port ps2Mouse=new PS2Mouse(); //声明一个PS2接口的鼠标 32 USBPort usb=new PS2ToUSB(ps2Mouse); //把PS2接口的鼠标通过Adapter转成USB接口 33 computer.connectMouse(usb); //这样电脑就可以正常连接使用PS2接口的鼠标了。 34 35 } 36 }
类Adapter:
1 interface USBPort{ //定义USB接口 2 void workWithUSB(); 3 } 4 interface PS2Port{ //定义PS2接口 5 void workWithPS2(); 6 } 7 class PS2Mouse implements PS2Port{ //定义PS2接口鼠标实现PS2Port 8 public void workWithPS2(){ 9 System.out.println("使用PS2接口连接工作"); 10 } 11 } 12 /* 13 *此类为对象Adapter模式 14 * 15 class PS2ToUSB implements USBPort{ 16 private PS2Port ps2Port=null; //存放一个PS2Port的对象引用 17 public PS2ToUSB(PS2Port ps2Port){ 18 this.ps2Port=ps2Port; 19 } 20 public void workWithUSB(){ 21 ps2Port.workWithPS2(); //调用PS2Port对象的workWithPS2()方法 22 } 23 } 24 */ 25 /* 26 * 此类为类Adapter模式 27 */ 28 class Adapter implements PS2Port,USBPort{ 29 private PS2Port ps2=null; 30 public Adapter(PS2Port ps2){ 31 this.ps2=ps2; 32 } 33 public void workWithUSB(){ 34 this.ps2.workWithPS2(); 35 } 36 public void workWithPS2(){ 37 this.ps2.workWithPS2(); 38 } 39 40 } 41 class Computer{ //定义一个Computer,没有PS2插孔,只能连USB鼠标 42 43 public void connectMouse(USBPort usb){ //连接USB鼠标 44 usb.workWithUSB(); 45 } 46 } 47 public class AdapterDemo{ 48 public static void main(String args[]){ 49 50 Computer computer=new Computer(); //声明一个电脑对象,但是电脑正常使用只能接受USB接口的鼠标 51 PS2Port ps2Mouse=new PS2Mouse(); //声明一个PS2接口的鼠标 52 //USBPort usb=new PS2ToUSB(ps2Mouse); //把PS2接口的鼠标通过Adapter转成USB接口 53 Adapter adapter=new Adapter(ps2Mouse); 54 computer.connectMouse(adapter); //这样电脑就可以正常连接使用PS2接口的鼠标了。 55 56 } 57 }
浙公网安备 33010602011771号