Structual设计--Adapter模式

来源:互联网 发布:java正则表达式 可选 编辑:程序博客网 时间:2024/04/30 12:02

1.意图

将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原来由于接口不兼容而不能在一起工作的那些类可以在一起工作。

2.别名

包装器Wrapper。

3.动机

有时,为复用而设计的工具箱类不能够被复用原因仅仅是因为它的接口与专业应用领域所需要的接口不匹配。具体场景可以描述为:基础功能类–》adapter专业接口–》专业调用,其中基础功能类可以理解为我们常见的jdk,也可以是一些sdk或者一些平台支持类。

4.适用性

以下情况使用Adapter模式

  • 你想使用一个已经存在的类,而它的接口不符合你的要求
  • 你想创建一个可以复用的类,该类可以与其他不相关的类或者不可预见的类(即那些接口可能不一定兼容的类)协同工作。
  • (仅适用于对象Adapter)你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配他们的接口。对象适配器可以是适配它的父类接口。

5.结构

类适配器使用多重继承对一个接口与另一个接口进行匹配,如下图所示,旨在让Targetable具有Source类功能,本身不对Source类做操作:
类适配器

对象适配器依赖于对象组合,如下图所示,思路和类适配器是一样的,只是这里不再继承Source类,而是持有Source类对象的实例,以达到解决兼容性问题。
对象适配器模式

6.代码示例

类适配器代码:
Source类

public class Source {    public void method1() {        System.out.println("this is original method!");    }}

Targetable类

public interface Targetable {    /* 与原类中的方法相同 */    public void method1();    /* 新类的方法 */    public void method2();}

适配器adapter类

public class Adapter extends Source implements Targetable {    @Override    public void method2() {        System.out.println("this is the targetable method!");    }}

Adapter类继承Source类,实现Targetable接口,下面是测试类:

public class AdapterTest {    public static void main(String[] args) {        Targetable target = new Adapter();        target.method1();        target.method2();    }}

输出结果:
this is original method!
this is the targetable method!
这样Targetable接口的实现类就具有了Source类的功能。

类对象适配器代码:
只需要修改Adapter类的源码即可:

public class Wrapper implements Targetable {    private Source source;    public Wrapper(Source source){        super();        this.source = source;    }    @Override    public void method2() {        System.out.println("this is the targetable method!");    }    @Override    public void method1() {        source.method1();    }}

测试类:

public class AdapterTest {    public static void main(String[] args) {        Source source = new Source();        Targetable target = new Wrapper(source);        target.method1();        target.method2();    }}

输出与第一种一样,只是适配的方法不同而已。

7.相关模式

模式Bridge的结构与对象适配器类似,但是Bridge模式的出发点不同:Bridge目的是将接口部分和实现部分分离,从而对他们可以较为容易也相对独立的加以改变。而Adapter则意味着改变一个已有对象的接口。
Decorator模式增加了其他对象的功能而同时又不改变他的接口。因此decorator对应用应用程序的透明性比适配器要好。结果是decorator支持递归组合,而纯粹使用适配器是不可能实现这一点的。
模式Proxy在不改变它的接口的条件下,为另一个对象定义了一个代理。

引用:

http://item.jd.com/10057319.html
http://blog.csdn.net/zhangerqing/article/details/8239539

0 0
原创粉丝点击