设计模式(七)之 Adapter(适配器)
来源:互联网 发布:mysql 表触发器 编辑:程序博客网 时间:2024/05/17 07:58
定义:
将两个不兼容的类纠合在一起使用,属于结构型模式,需要有 Adaptee(被适配者)和Adaptor(适配器)两个身份.
为何使用?
我们经常碰到要将两个没有关系的类组合在一起使用,第一解决方案是: 修改各自类的接口,但是如果我们没有源代码,或者,我们不愿意为了一个应用而修改各自的接口。 怎么办?
使用 Adapter,在这两种接口之间创建一个混合接口(混血儿).
如何使用?
实现 Adapter 方式,其实"think in Java"的"类再生"一节中已经提到,有两种方式:组合
(composition)和继承(inheritance).
假设我们要打桩,有两种类:方形桩 圆形桩.
public class SquarePeg{public void insert(String str){System.out.println("SquarePeg insert():"+str);}}public class RoundPeg{public void insertIntohole(String msg){System.out.println("RoundPeg insertIntoHole():"+msg);}}
现在有一个应用,需要既打方形桩,又打圆形桩.那么我们需要将这两个没有关系的类综合应
用.假设RoundPeg我们没有源代码,或源代码我们不想修改,那么我们使用Adapter来实现这
个应用:
public class PegAdapter extends SquarePeg{private RoundPeg roundPeg;public PegAdapter(RoundPeg peg)(this.roundPeg=peg;)public void insert(String str){ roundPeg.insertIntoHole(str);}}
适配者 RoundPeg)和 Target(目标 SquarePeg)进行适配.实际上这是将组合方法
(composition)和继承(inheritance)方法综合运用.
PegAdapter 首先继承 SquarePeg,然后使用 new 的组合生成对象方式,生成 RoundPeg 的对
象 roundPeg, 再重载父类 insert()方法。 从这里,你也了解使用 new 生成对象和使用 extends
继承生成对象的不同,前者无需对原来的类修改,甚至无需要知道其内部结构和源代码.
如果你有些 Java 使用的经验,已经发现,这种模式经常使用。
进一步使用
上面的 PegAdapter 是继承了 SquarePeg,如果我们需要两边继承, 即继承 SquarePeg 又继承RoundPeg,因为 Java 中不允许多继承,但是我们可以实现(implements)两个接口
(interface)
public interface IRoundPeg{public void insertIntoHole(String msg);}public interface ISquarePeg{public void insert(String str);}下面是新的 RoundPeg 和 SquarePeg, 除了实现接口这一区别,和上面的没什么区别。public class SquarePeg implements ISquarePeg{public void insert(String str){System.out.println("SquarePeg insert():"+str);}}public class RoundPeg implements IRoundPeg{public void insertIntohole(String msg){System.out.println("RoundPeg insertIntoHole():"+msg);}}下面是新的 PegAdapter,叫做 two-way adapter:public class PegAdapter implements IRoundPeg,ISquarePeg{private RoundPeg roundPeg;private SquarePeg squarePeg;// 构造方法public PegAdapter(RoundPeg peg){this.roundPeg=peg;}// 构造方法public PegAdapter(SquarePeg peg)(this.squarePeg=peg;)public void insert(String str){ roundPeg.insertIntoHole(str);}}
还有一种叫 Pluggable Adapters,可以动态的获取几个 adapters 中一个。使用 Reflection
技术,可以动态的发现类中的 Public 方法。
0 0
- 设计模式(七)之 Adapter(适配器)
- 设计模式之(七)适配器模式Adapter
- 设计模式之七 ------Adapter(适配器)
- 设计模式学习笔记(七)之适配器模式(Adapter)
- 设计模式之--适配器模式(adapter)
- 设计模式之Adapter(适配器模式)
- 设计模式之适配器(Adapter)模式
- 设计模式之--适配器模式(adapter)
- 设计模式之适配器模式(Adapter)
- 设计模式之--适配器模式(adapter)
- 设计模式之适配器模式(Adapter)
- 设计模式之--适配器模式(adapter)
- 设计模式之Adapter(适配器)模式
- 设计模式之适配器模式(Adapter)
- 设计模式之(Adapter)适配器模式
- 设计模式之适配器模式(Adapter)
- 设计模式之适配器模式(Adapter)
- 设计模式之适配器模式(Adapter)
- 泛型
- IOS开发 单例模式
- ScheduledExecutorService定时周期执行指定的任务
- mysql sql语句大全
- HDU 2089
- 设计模式(七)之 Adapter(适配器)
- iOS 单例
- 利用百度地图api写的一个获取经纬度和精度半径的类
- poj2503--Babelfish(字典树一水)
- 黑马程序员_OC类的声明和实现以及常见错误
- SolrQParserPlugin 理解内部调用过程
- 黑马程序员_Java基础02天日志
- 利用php脚本将文本文件中的数据导入到mysql数据库中
- OC 字符串