示例类图
![8195388-2372891df3aed2ad.png](https://i-blog.csdnimg.cn/blog_migrate/570cd78fca9c8475bdde3822ebd2e3b3.webp?x-image-process=image/format,png)
对象适配器模式.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目标方法
被适配者的方法