java适配器模式

来源:互联网 发布:网络版点歌软件 编辑:程序博客网 时间:2024/06/07 03:08

http://www.blogjava.net/fancydeepin/archive/2012/08/05/java_pattern_Adapter.html

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

1. 类的适配器模式结构图:



从图中可以看出,Adaptee 类(源类)并没有 operation2() 这个方法,而客户端正期待这个方法,为使客户端能够使用 Adaptee 类,在此为其提供了一个中间环节,

即 Adapter 类(适配器类),把 Adaptee 的 API 与 Target 的 API 衔接起来,在这里,Adapter 与 Adaptee 是继承关系,这就决定了这个适配器的模式是类。

示意图的实现源码:

package pattern.adapter;/** * ----------------------------------------- * @描述  源类(需要适配的类) * @作者  fancy * @邮箱  fancydeepin@yeah.net * @日期  2012-8-5 <p> * ----------------------------------------- */public class Adaptee {    public void operation1(){                //do other things here    }}package pattern.adapter;/** * ----------------------------------------- * @描述  目标接口 * @作者  fancy * @邮箱  fancydeepin@yeah.net * @日期  2012-8-5 <p> * ----------------------------------------- */public interface Target {    public void operation1();        public void operation2();    }package pattern.adapter;/** * ----------------------------------------- * @描述  适配器 * @作者  fancy * @邮箱  fancydeepin@yeah.net * @日期  2012-8-5 <p> * ----------------------------------------- */public class Adapter extends Adaptee implements Target{    public void operation2(){                //do other things here    }}



2. 对象的适配器模式结构图:



从图中可以看出,Adaptee 类(源类)并没有 operation2() 这个方法,而客户端正期待这个方法,为使客户端能够使用 Adaptee 类,在此为其提供了一个包装类,

即 Adapter 类(适配器类),它包装了一个 Adaptee 类的实例,从而此包装类能够把 Adaptee 的 API 与 Target 的 API 衔接起来,在这里,Adapter 与 Adaptee 是委派关系,

这就决定了这个适配器的模式是对象。

示意图中的 Target 和 Adaptee 源代码不变,下面来看一下 Adapter 类的源码:




package pattern.adapter;/** * ----------------------------------------- * @描述  适配器 * @作者  fancy * @邮箱  fancydeepin@yeah.net * @日期  2012-8-5 <p> * ----------------------------------------- */public class Adapter implements Target{    private Adaptee adaptee;        public Adapter(Adaptee adaptee){        this.adaptee = adaptee;    }        @Override    public void operation1() {                adaptee.operation1();    }    @Override    public void operation2() {                //do other things here    }}



原创粉丝点击