适配器模式

设计模式/结构型设计模式

简述

  • 将一个类的接口转换成希望的另一个接口,使接口兼容另一个类
  • 模式组成
    1. 目标角色
    2. 被适配角色
    3. 适配器角色

UML图

2种模式

适配器模式可以分为:类适配器模式和对象适配器模式

类适配器模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//目标接口
public interface Comfortable {
void comfort();
}

//适配者
@Slf4j
public class Cat implements Animal {
public void run() {
log.info("猫 —> 🐱");
}
}

//类适配器类
public class CatAdapter extends Cat implements Comfortable {

public void comfort() {
run();
}
}

//客户端代码
public class Client {
public static void main(String[] args) {
// 类适配
Comfortable catAdapter = new CatAdapter();
catAdapter.comfort();
//对象适配
Comfortable dogAdapter = new DogAdapter(new Dog());
dogAdapter.comfort();
}
}

对象适配器模式

1
2
3
4
5
6
7
8
9
10
public class DogAdapter implements Comfortable {
private Dog dog;
public DogAdapter(Dog dog) {
this.dog = dog;
}

public void comfort() {
dog.run();
}
}

小结

  • 类适配器使用的是继承的方式,直接继承了Adapter,
    所以无法对Adapter的子类进行适配
  • 对象适配器使用的是组合的方式,所以Adapter及其子孙类都可以被适配。
    另外,对象适配器对于增加一些新行为非常方便,而且新增加的行为同时适用于所有的源