Adapter模式

package JAVABasic;

/**
 * 1、目标(Target):这就是所期待获得的接口。
 * 2、源(Adaptee):现有须要适配的接口。
 * 3、适配器(Adapter):适配器类是本模式的核心。适配器把源接口转换成目标接口。 
 * @author markGao
 *
 */
public class AdapterMode {
    public static void main(String[] args) {
        Target a = new Adapter();
        a.sampleOperation1();
        a.sampleOperation2();
    }

}

class Adaptee {
    public void sampleOperation1() {
        System.out.println("方法名       "
                + Thread.currentThread().getStackTrace()[1].getMethodName());
        System.out.println("类名    "
                + Thread.currentThread().getStackTrace()[1].getClassName());
    }
}

interface Target {
    /**
     * Class Adaptee contains operation sampleOperation1.
     */
    void sampleOperation1();

    /**
     * Class Adaptee doesn't contain operation sampleOperation2.
     */
    void sampleOperation2();
}

class Adapter extends Adaptee implements Target {
    /**
     * Class Adaptee doesn't contain operation sampleOperation2.
     */
    public void sampleOperation2() {
        // Write your code here
        System.out.println("文件名   "
                + Thread.currentThread().getStackTrace()[1].getFileName());
        System.out.println("所在的行数 "
                + Thread.currentThread().getStackTrace()[1].getLineNumber());

    }
}

在咱们实际生活中也很容易看到这方面的例子,好比咱们要和一个外国人打交道,例如韩国 人,若是咱们没有学习过韩语,这个韩国人也没有学习过咱们汉语,在这种状况下,咱们之间是很难进行直接交流沟通。为了达到沟通的目的有两个方法:1)改造 这个韩国人,使其可以用汉语进行沟通;2)请一个翻译,在咱们和这个韩国人之间进行语言的协调。显然第一种方式——改造这个韩国人的代价要高一些,咱们不 仅要从新培训他汉语的学习,还有时间、态度等等因素。而第二个方式——请一个翻译,就很好实现,并且成本低,还比较灵活,当咱们想换个日本人,再换个翻译 就能够了。java


在GOF设计模式中,Adapter能够分为类模式和对象模式两种,类模式经过多重继承实现,对象模式经过委托实现。设计模式

在Java中因为没有多重继承机制,因此要想实现类模式的Adapter,就要进行相应 的改变:经过继承Adaptee类实现Target接口方式实现。这种改变存在两个问题:1)Target必须是一个接口而不能是一个类,不然 Adapter没法implements实现;2)Adapter是继承Adaptee的实现,而不是私有继承,这就表示Adapter是一个 Adaptee的子类。学习

相关文章
相关标签/搜索