适配器模式
来源:互联网 发布:gta4优化补丁告别卡顿 编辑:程序博客网 时间:2024/06/05 20:25
适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
优点:适配器可以在不改变原有代码的情况下让原本不兼容的类无间合作
缺点:过多的使用适配器,会让系统变得凌乱
适配器模式分为类适配器和对象适配器模式!!
一:类适配器
类的适配器模式把适配的类的API转换成为目标类的API。
/** * 类适配模式 * @author Xul * */public class AdapterModel { public static void main(String[] args) { Target target = new Adapter(); target.zuofan(); }}/** * 目标接口 * 做饭 */interface Target{ public void zuofan();}/** * 需要被适配的接口 */class Adaptee{ public void maicai(){ System.out.println("买菜!!!"); } public void shaoshui(){ System.out.println("烧水!!!"); } public void zhufan(){ System.out.println("煮饭!!!"); } public void chaocai(){ System.out.println("炒菜!!!"); }}/** * 适配器 */class Adapter extends Adaptee implements Target{ @Override public void zuofan() { this.maicai(); this.shaoshui(); this.zhufan(); this.chaocai(); }}
二:对象适配器
对象的适配器模式使用委派关系连接到Adaptee类,把被适配的类的API转换成为目标类的API
/** * 对象适配器模式 */public class ObjAdapterModel { public static void main(String[] args) { ObjAdaptee adaptee = new ObjAdaptee(); ObjTarget objTarget = new ObjAdapter(adaptee); objTarget.zuofan(); }}/** * 目标接口 * 做饭 */interface ObjTarget{ public void zuofan();}/** * 需要被适配的接口 */class ObjAdaptee{ public void maicai(){ System.out.println("买菜!!!"); } public void shaoshui(){ System.out.println("烧水!!!"); } public void zhufan(){ System.out.println("煮饭!!!"); } public void chaocai(){ System.out.println("炒菜!!!"); }}/** * 适配器 */class ObjAdapter implements ObjTarget{ ObjAdaptee objAdaptee ; public ObjAdapter(ObjAdaptee objAdaptee) { this.objAdaptee = objAdaptee; } @Override public void zuofan() { objAdaptee.maicai(); objAdaptee.shaoshui(); objAdaptee.zhufan(); objAdaptee.chaocai(); }}
0 0
- 适配器及适配器模式
- 适配器及适配器模式
- 适配器模式(类适配器)
- 适配器模式(默认适配器)
- 适配器模式(对象适配器)
- 适配器模式-类适配器
- 适配器模式-对象适配器
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- nios 中出现undefined reference to `__alt_invalid'alt_sys_init.c CC++ Problem的解决方法
- GO语言构建高并发分布式系统实践
- 代码中获取控件的宽高度,代码中设置控件的Margin
- ROS节点与运行
- mysql 动态生成sql语句执行方法,表格重新产生排序
- 适配器模式
- Unity Gameplay工具集(Unity Gameplay Tool Set)
- mvc配置加载类
- 有关windows RASDIAL
- centOS 安装 pip
- 基于qq.maps.com的web地图定位导航
- N皇后
- 解决上传大文件失败的问题
- 李白打酒