结构型设计模式-适配器模式
2017-03-03 10:16
197 查看
适配器模式:类适配器模式(继承)和对象适配器模式(内部组件)
将一个类的接口转换成客户希望的另外一个接口,
Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式参与角色:
目标接口(Target):客户所期待的接口,目标可以是具体的或抽象的类,也可以是接口。
适配源(Adaptee):需要适配的类或适配者类。
适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
适配器模式———————————————–类适配
目标接口:Target
适配源:ClassAdaptee
适配器:ClassAdapter
类适配测试代码:
适配器模式———————————————–对象适配
适配源:ObjectAdaptee
适配器:ObjectAdapter
测试代码:
结果:
适配器模式分析:
适配器个人觉得和代理模式类似,只是出发点不同而已,代理模式是以目标对象为主体,进行对应的功能代理,提供给客户端访问,适配器则是以客户端为主体,通过代理适配源对象的方法,并将其转换为客户要求的形式
将一个类的接口转换成客户希望的另外一个接口,
Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式参与角色:
目标接口(Target):客户所期待的接口,目标可以是具体的或抽象的类,也可以是接口。
适配源(Adaptee):需要适配的类或适配者类。
适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
适配器模式———————————————–类适配
目标接口:Target
package com.zhiwei.adapter; public interface Target { public void request(); }
适配源:ClassAdaptee
package com.zhiwei.adapter; public class ClassAdaptee { public void show(){ System.out.println("适配源类方法正在执行......"); } }
适配器:ClassAdapter
package com.zhiwei.adapter; public class ClassAdapter extends ClassAdaptee implements Target{ @Override public void request(){ super.show(); //调用父类ClassAdaptee的方法处理 } }
类适配测试代码:
//类适配 Target client = new ClassAdapter(); client.request();
适配器模式———————————————–对象适配
适配源:ObjectAdaptee
package com.zhiwei.adapter; public class ObjectAdaptee { public void show(){ System.out.println("适配源对象方法正在执行......"); } }
适配器:ObjectAdapter
package com.zhiwei.adapter; public class ObjectAdapter implements Target{ private ObjectAdaptee objectAdaptee; //适配源可以定义为统一的接口,这样适配的范围从一类对象拓展至接口管理的所有对象 public ObjectAdapter(ObjectAdaptee objectAdaptee) { this.objectAdaptee = objectAdaptee; } @Override public void request() { objectAdaptee.show(); } }
测试代码:
//创建适配源对象 ObjectAdaptee objectAdaptee = new ObjectAdaptee(); //适配器适配适配源对象 Target target = new ObjectAdapter(objectAdaptee); //调用客户端方法 target.request();
结果:
适配器模式分析:
适配器个人觉得和代理模式类似,只是出发点不同而已,代理模式是以目标对象为主体,进行对应的功能代理,提供给客户端访问,适配器则是以客户端为主体,通过代理适配源对象的方法,并将其转换为客户要求的形式
相关文章推荐
- 白话设计模式--结构型模式--组合模式,桥接模式和适配器模式
- 结构型设计模式---Adapter模式(适配器模式)
- 设计模式--结构型--适配器模式
- java设计模式(结构型)之适配器模式
- 设计模式(6) 结构型模式和适配器模式(ADAPTER)
- 九.结构型设计模式——Adapter Pattern(适配器模式)
- 设计模式(五)适配器模式Adapter(结构型)
- [设计模式笔记]二. 结构型模式--7.Adapter模式(适配器模式)(一)
- 设计模式--适配器模式Adapter(结构型)
- 设计模式笔记 6.Adapter 适配器模式(结构型模式)
- 设计模式笔记(7)---适配器模式(结构型)
- 设计模式(五)适配器模式Adapter(结构型)
- 设计模式笔记(7)---适配器模式(结构型)
- GoF23种设计模式之结构型模式之适配器模式
- 设计模式笔记(7)---适配器模式(结构型)
- 设计模式 一 适配器模式 Adapter(结构型模式)
- 设计模式(6)-结构型-适配器模式(Adapter)(个人笔记)
- 设计模式7——结构型模式之适配器模式
- 设计模式7——结构型模式之适配器模式
- 白话设计模式 --结构型模式--装饰者(Decorator)模式,适配器模式和外观模式