适配器模式:
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
模式中的角色:
--目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类。也可以是接口。
--需要适配的对象(Adaptee):需要适配的类或者适配者类。
--适配器(Adapter):通过包装一个需要适配的对象,把原接口转化成目标接口。
这里我们以 笔记本,ps/2键盘 为例,笔记本只支持usb,那我们就需要生产一个支持usb和ps/2转换的适配器,笔记本相当于客户端(client)、键盘相当于被适配的对象(adaptee),转接器相当于适配器(adapter)
package com.gof.adapter;/** * 被适配的类 * (相当于例子中的,ps/2键盘) * @author root * */public class Adaptee { public void request() { System.out.println("可以完成客户需要的功能!"); }}
package com.gof.adapter;/** * 客户端类 * (相当于例子中的笔记本,只有usb) * @author root * */public class Client { public void test1(Target t ) { t.handleReq(); } public static void main(String[] args) { Client client = new Client(); Adaptee adaptee = new Adaptee(); Adapter adapter = new Adapter(); client.test1(adapter); }}
package com.gof.adapter;/** * 这个是笔记本的usb功能 * @author root * */public interface Target { void handleReq();}
package com.gof.adapter;/** * 适配器本身 * (相当于usb和ps/2的转换器) * @author root * */public class Adapter extends Adaptee implements Target{ @Override public void handleReq() { super.request(); }}
注:上述适配器采用的是继承的方式、缺点是不能再继承其他的类了。
方法二:对象适配器、采用组合的方式
修改适配器,和客户端调用
package com.gof.adapter;/** * 适配器本身 * (相当于usb和ps/2的转换器) * @author root * */public class Adapter2 implements Target{ private Adaptee adaptee; @Override public void handleReq() { adaptee.request(); } public Adapter2(Adaptee adaptee) { super(); this.adaptee = adaptee; } }
package com.gof.adapter;/** * 客户端类 * (相当于例子中的笔记本,只有usb) * @author root * */public class Client2 { public void test1(Target t ) { t.handleReq(); } public static void main(String[] args) { Client2 client = new Client2(); Adaptee adaptee = new Adaptee(); Adapter2 Adapter2 = new Adapter2(adaptee); client.test1(Adapter2); }}
常用场景: