package adapter; /** * @author jiq * 类型:Structural * 定义: 适配器模式将一个类的接口,转换成客户期望的另一个接口。适配器模式让原本 * 接口不兼容的类,现在可以合作无间。 * * OO原则:使用对象组合,以修改的接口来包装被适配者。 * 我们绑定的是客户(使用适配器一方)和接口,而不是绑定客户和实现。 * * 与装饰器模式的区别: 适配器模式“将一个接口转换成另一个接口”, * 而装饰器模式“不改变任何接口,而是加入新的责任”。 * * 分类: 对象适配器(如下实例),类适配器(不常用) * * 另外一个改变接口的模式: Facade(外观)模式,但是它改变接口的原因是为了简化接口。 * * 代码说明: 我有一个显示器Monitor,是用来显示图形的,它只能接收来自图形发送设备 * GrapTransmitter的信号,但是我现在只有一个CPU,他所能产生的数据无法被显示器 * 识别,即这两个设备不是兼容的。 这个时候我们就需要一个图形适配器GrapAdapter, * 能够将CPU适配于显示器。 */ //显示器 class Monitor{ GrapTransmitter gt; public Monitor(GrapTransmitter gt){ this.gt = gt; } //显示图形发送设备发送过来的图形数据 public void showGrap(){ System.out.println(gt.getGrapData()); } } //图形发送设备 class GrapTransmitter{ public String getGrapData(){ return "grap Content"; } } //现在我只有一个CPU class CPU{ //只能产生CPU数据 public int getCpuData(){ return 10; } } /** * 我们需要一个图形适配器,继承某一方(如这里GrapTransmitter), * 同时内部包含一个被适配的类(CPU),通过重写其父类的方法来进行适配。 * */ class GrapAdapter extends GrapTransmitter{ private CPU cpu; //组合被适配的类 public GrapAdapter(CPU cpu){ this.cpu = cpu; } //重写父类的接口 public String getGrapData(){ return String.valueOf(cpu.getCpuData()); } } public class Adapter { public static void main(String[] args) { //用图形适配器包装CPU,转换成显示器期望的图形发送设备 GrapTransmitter gt = new GrapAdapter(new CPU()); //利用该图形发送设备创建一个显示器 Monitor monitor = new Monitor(gt); monitor.showGrap(); } }/** * output: 10 */