S03 适配器模式 示例(二) 对象适配器

示例类图

S03 适配器模式 示例(二) 对象适配器
对象适配器模式.png

示例代码

  • 用组合的方式适配了现有类Adaptee;
public class Adaptee {
    public void adapteeRequest(){
        System.out.println("被适配者的方法");
    }
}

public interface Target {
    void request();
}

public class Adaptor implements Target {
    Adaptee adaptee = new Adaptee();
    @Override
    public void request() {
        // ...
        adaptee.adapteeRequest();
        // ...
    }
}

public class ConcreteTarget implements Target {
    @Override
    public void request() {
        System.out.println("concreteTarget目标方法");
    }
}

public class Test {
    public static void main(String[] args) {
        Target target = new ConcreteTarget();
        target.request();

        Target adapterTarget = new Adaptor();
        adapterTarget.request();
    }
}

输出:

concreteTarget目标方法
被适配者的方法