适配器模式

1.定义

适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。

2.具体实现

2.1代码

  1. 类适配器模式的代码如下:
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
package 设计模式;

public class ClassAdapterPattern {
public static void main(String[] args) {
Target target = new ClassAdapter();
target.request();
}
}
//目标接口
interface Target {
void request();
}
//适配者接口
class Adaptee {
public void specificRequest() {
System.out.println("正在适配中.....");
}
}
//类适配器类
class ClassAdapter extends Adaptee implements Target {
@Override
public void request() {
specificRequest();
}
}

  1. 对象适配器模式的代码如下:
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
public class ObjectAdapterPattern {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new ObjectAdapter(adaptee);
target.request();
}
}
//目标接口
interface Target {
void request();
}
//适配者接口
class Adaptee {
public void specificRequest() {
System.out.println("正在适配中.....");
}
}
//对象适配器类
class ObjectAdapter implements Target {
private Adaptee adaptee;
public ObjectAdapter(Adaptee adaptee) {
this.adaptee=adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}

3.优点

  • 将目标类和适配者类解耦
  • 增加了类的透明性和复用性,将具体的实现封装在适配者类中,对于客户端类来说是透明的,而且提高了适配者的复用性
  • 灵活性和扩展性都非常好,符合开闭原则

4.缺点

  • 类适配器,对于Java不支持多重继承的语言,一次最多只能适配一个适配者类,而且目标抽象类只能为接口,不能为类,其使用有一定的局限性,不能将一个适配者类和他的子类同时适配到目标接口。所以多用对象适配器。

5.使用场景

  • 接口中规定了所有要实现的方法
  • 但一个要实现此接口的具体类,只用到了其中的几个方法,而其它的方法都是没有用的。