什么是适配器模式?
将一个类的接口转换成客户希望的另一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
模式中的角色:
目标接口(target):客户所期待的接口。目标可以是具体的或者抽象的类,也可以是接口。
需要适配的类(Adaptee):需要适配的类或适配者类。
适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口
类图:
以键盘和pc操作为例
创建一个适配接口:
package com.gcxzflgl.adapter; public interface Target { void handleReq(); }
创建被适配的类
package com.gcxzflgl.adapter; /** * 被适配的类 * (相当于例子中的,PS/2键盘) * @author Administrator * */ public class Adaptee { public void request(){ System.out.println("可以完成客户请求的需要的功能!"); } }
创建适配器:
package com.gcxzflgl.adapter; /** * 适配器 (对象适配器方式,使用了组合的方式跟被适配对象整合) * (相当于usb和ps/2的转接器) * @author Administrator * */ public class Adapter2 implements Target { private Adaptee adaptee; @Override public void handleReq() { adaptee.request(); } public Adapter2(Adaptee adaptee) { super(); this.adaptee = adaptee; } }
模拟客户端进行调用:
package com.gcxzflgl.adapter; /** * 客户端类 * (相当于例子中的笔记本,只有USB接口) * @author Administrator * */ public class Client { public void test1(Target t){ t.handleReq(); } public static void main(String[] args) { Client c = new Client(); Adaptee a = new Adaptee(); Target t = new Adapter2(a); c.test1(t); } }