针对问题:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。——Gang of Four
适配器模式结构图:
适配器模式实现代码:
/** * 现实存在的接口 * @author bruce * */ public interface Adaptee { public void specificRequest(); } /** * 客户期望的接口 * @author bruce * */ public interface Target { public void request(); } /** * 适配器 * @author bruce * */ public class Adapter implements Target{ private Adaptee adaptee;//组合现实存在的接口 public Adapter(Adaptee adaptee){ this.adaptee=adaptee; } public void request() { // TODO Auto-generated method stub adaptee.specificRequest(); } } /** * 现实存在的类 * @author bruce * */ public class ConcreteAdaptee implements Adaptee{ public void specificRequest() { // TODO Auto-generated method stub } } /** * 将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。——Gang of Four */ /** * 测试 * @author bruce * */ public class Client { public static void main(String[] args) { Adaptee adaptee=new ConcreteAdaptee(); //根据已存在的类创建对象 Adapter adapter=new Adapter(adaptee); //继承目标接口并组合已存在的对象来生成适配器 adapter.request(); //可以调用该接口了 } }