1.定义
- 将一个类的接口转换为客户期待的接口(通过Adapter达到兼容接口的目的)
2.UML类图
- 角色介绍
IAccessSDCardTarget : Target角色,定义了目标接口
TFCardAdaptee : Adaptee角色,需要适配的角色,将其接口适配为Target定义的接口
AccessAdapter : Adapter角色,这里为对象适配器角色,Adapter通过代理的方式与Adaptee连接 - 要点
Adapter需要实现Target接口,并且代理使用Adaptee对象
3.UML示例代码
/**
* Copyright (C), 2016-2020
* FileName: IAccessSDCardTarget
* Author: wei.zheng
* Date: 2020/1/4 10:05
* Description: Target角色,抽象接口,读写SDCard
*/
public interface IAccessSDCardTarget {
String readSDCard();
void writeSDCard(String content);
}
/**
* Copyright (C), 2016-2020
* FileName: TFCardAdaptee
* Author: wei.zheng
* Date: 2020/1/4 10:06
* Description: Adaptee角色, 需要适配的角色,TFCard读写具体类
*/
public class TFCardAdaptee {
public String readTFCard() {
return "Hello, I am TF Card.";
}
public void writeTFCard(String content) {
System.out.println("TF Card write success:" + content);
}
}
/**
* Copyright (C), 2016-2020
* FileName: AccessApdapter
* Author: wei.zheng
* Date: 2020/1/4 10:09
* Description: Adapter角色,适配TFCardAdaptee (代理的方式连接到Adaptee角色)
*/
public class AccessApdapter implements IAccessSDCardTarget {
private TFCardAdaptee tfCardAdaptee;
public AccessApdapter(TFCardAdaptee tfCardAdaptee) {
this.tfCardAdaptee = tfCardAdaptee;
}
@Override
public String readSDCard() {
return tfCardAdaptee.readTFCard();
}
@Override
public void writeSDCard(String content) {
tfCardAdaptee.writeTFCard(content);
}
}
/**
* Copyright (C), 2016-2020
* FileName: Client
* Author: wei.zheng
* Date: 2020/1/4 10:12
* Description: 适配器模式用户类 (这里实为对象适配器模式)
*/
public class Client {
public static void main(String[] args) {
TFCardAdaptee tfCardAdaptee = new TFCardAdaptee();
AccessApdapter accessApdapter = new AccessApdapter(tfCardAdaptee);
String readResult = accessApdapter.readSDCard();
System.out.println("readResult:" + readResult);
accessApdapter.writeSDCard("Record adapter pattern uml code.");
}
}
// 运行结果
2020-01-04 10:18:10.903 11631-11631/? I/System.out: readResult:Hello, I am TF Card.
2020-01-04 10:18:10.903 11631-11631/? I/System.out: TF Card write success:Record adapter pattern uml code.
4.总结
适配器模式应用广泛,必须掌握的基础设计模式。
优点:
接口兼容,提高类的复用性;
使用Adapter,提高了系统的可扩展性
缺点:
Adapter的本质为接口转换,使用过多,降低代码可读性