适配器模式(Adapter Pattern)把一个类的接口变换成客户端所期待的的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
模式所涉及的角色有:
下面以一个例子来说明适配器模式:
假设系统是一个银行系统,只提供取款功能,目前只有两个类:
类:BankAdaptee
public class BankAdaptee { /** * 银行提供人民币业务 */ public void withdrawRMB(){ System.out.println("本银行只提供人民币业务"); } }
类:Client
public class Client { public static void main(String[] args) { BankAdaptee orignal = new BankAdaptee(); orignal.withdrawRMB(); } }
通过运行Client类可查询出该银行现有的业务,结果如下所示:
那么,我如果想要在不改变原来系统的功能下让该银行实现对于美元、日元的业务处理呢?看代码:
添加接口:Target,该接口中指定用户想要实现的功能
/** * * 该接口中抽象出客户想要实现的功能 * */ public interface Target { /** * 银行对于人民币业务的处理 */ void withdrawRMB(); /** * 银行对于美元业务的处理 */ void withdrawDollar(); /** * 银行对于日元业务的处理 */ void withdrawJPY(); }
添加适配器Adapter:
public class BankAdapter extends BankAdaptee implements Target{ @Override public void withdrawDollar() { System.out.println("通过适配器模式,银行新增有美元业务"); } @Override public void withdrawJPY() { System.out.println("通过适配器模式,银行新增有日元业务"); } }
修改Client类:
public class Client { public static void main(String[] args) { /*BankAdaptee orignal = new BankAdaptee(); orignal.withdrawRMB();*/ BankAdapter now = new BankAdapter(); now.withdrawRMB(); now.withdrawJPY(); now.withdrawDollar(); } }
运行结果如下所示:
通过以上例子是不是发现,我们只需要在系统中重新添加代码而不需要修改系统中的代码了,是不是通过这种适配器模式很好地增加了系统的可维护性、重塑性呢。
原文:http://www.cnblogs.com/yourarebest/p/5125696.html