0%

适配器模式

前言:适配器模式

适配器模式(Adapter Pattern)

角色

目标接口(Target):客户所期望的接口。

适配类(Adaptee):需要适配的类。

适配器(Adapter):通过包装一个需要适配的对象,把原接口转成目标接口。

类图

image-20191226000849675

这是对象适配器模式,通过实现接口并在适配器中增加适配类实例属性,因为java是单继承,所以这种方式比类适配器模式好

代码

Adaptee

1
2
3
4
5
6
7
8
9
10
/**
* @author shency
* @description: TODO
* @date: 2019/11/5
*/
public class Adaptee {
public int output220V() {
return 220;
}
}

Target

1
2
3
4
5
6
7
8
/**
* @author shency
* @description: TODO
* @date: 2019/11/5
*/
public interface Target {
public int output5();
}

Adapter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @author shency
* @description: TODO
* @date: 2019/11/5
*/
public class Adapter implements Target{
private Adaptee adaptee;

public Adaptee getAdaptee() {
return adaptee;
}

public void setAdaptee(Adaptee adaptee) {
this.adaptee = adaptee;
}

@Override
public int output5() {
return adaptee.output220V()/44;
}
}

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @author shency
* @description: TODO
*/
public class Main {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Adapter adapter = new Adapter();
adapter.setAdaptee(adaptee);

Target target = adapter;
System.out.println(target.output5());
}
}
-------------本文结束感谢您的阅读-------------