适配器模式

2016-08-10  本文已影响0人  tdeblog

1.定义#

将一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。通过一个适配器类继承现有接口,并组合外部类到适配器类中。适配器模式一般在系统需要扩展时使用,是一种补救模式,不需要在设计之初使用。

2.类图#

类图

3.实现#

3.1目标类##

public interface Target {
    public String getContent();
}

3.2具体目标类##

public class ConcreteTarget implements Target {
    @Override
    public String getContent() {
        return "Target";
    }
}

3.3适配器类##

public class Adapter implements Target {

    private Adapter1 adapter1 = null;
    private Adapter2 adapter2 = null;

    public Adapter(Adapter1 _adapter1, Adapter2 _adapter2) {
        this.adapter1 = _adapter1;
        this.adapter2 = _adapter2;
    }
    @Override
    public String getContent() {
        return this.adapter1.SpecificRequest() + this.adapter2.SpecificRequest();
    }
}

3.4外部类##

public class Adapter1 {

    public String SpecificRequest(){
        return "specificRequest1";
    }
}

public class Adapter2 {

    public String SpecificRequest(){
        return "specificRequest2”;
    }
}

3.5客户端##

public class Client {
    public static void main(String args[]) {
        Target ct = new ConcreteTarget();
        System.out.println(ct.getContent());
        Target at = new Adapter(new Adapter1(), new Adapter2());
        System.out.println(at.getContent());
    }
}
上一篇 下一篇

猜你喜欢

热点阅读