java适配器模式(Adapter 模式)

适配器模式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
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值