適配器模式是把一個接口轉換成客戶端期待的另外一種接口,從而使本來由於接口不匹配而不能一塊兒工做的類可以一塊兒工做。java
適配器模式有兩種實現,一種是經過繼承實現(即:類適配器模式),另外一種是經過組合實現(即:對象適配器模式)ide
兩種模式的區別:this
類適配器模式:是經過繼承目標類,從而實如今適配器中對目標類方法的調用的spa
對象適配器模式:是經過將目標類聲明爲一個適配器的私有變量,從而實如今適配器中對目標類方法的調用的code
package com.hs.pattern.adapter; public interface Ps2 { public void ps2Input(); }
package com.hs.pattern.adapter; public class Usb { public void usbInput(){ System.out.println("this is usb"); } }
package com.hs.pattern.adapter; /** * 類適配器 * @author Administrator * */ public class UsbAdapter1 extends Usb implements Ps2 { @Override public void ps2Input() { usbInput(); } }
package com.hs.pattern.adapter; public class Client { public static void main(String[] args) { Ps2 ps2 = new UsbAdapter1(); ps2.ps2Input(); } }
package com.hs.pattern.adapter; /** * 對象適配器 * @author Administrator * */ public class UsbAdapter2 implements Ps2 { private Usb usb; public UsbAdapter2( Usb usb ){ this.usb = usb; } @Override public void ps2Input() { usb.usbInput(); } }
package com.hs.pattern.adapter; public class Client { public static void main(String[] args) { Usb usb = new Usb(); Ps2 ps2 = new UsbAdapter2(usb); ps2.ps2Input(); } }