示例类图

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目标方法
被适配者的方法

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
  • 2021-05-18
  • 2021-05-27
  • 2021-11-07
  • 2021-11-07
猜你喜欢
  • 2021-10-08
  • 2022-12-23
  • 2021-08-17
  • 2022-02-21
  • 2021-06-29
  • 2021-05-15
  • 2018-09-06
相关资源
相似解决方案