JAVA设计模式-适配器模式
1. 简介
- 什么是适配器模式?
- 将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作
- 适配器模式属于结构型模式
- 适配器实现了统一管理,一个目标是适配接口对象多个适配器类
- 优缺点?
- 优点:
- 增加了类的透明性和复用性,将具体的实现封装在适配者类中
- 对象适配器模式还可以将不通的适配者适配到同一个目标接口上
- 缺点:
- 过多的使用适配器类会让程序变得复杂
- 类适配器模式还存在单继承的问题
代码示例
/**
* @Author laijinhan
* @date 2020/9/13 10:49 上午
*/
import lombok.AllArgsConstructor;
/**
* 被适配的类
*/
class Adaptee{
public int outPut220V() {
System.out.println("输出220V的电压");
return 220;
}
}
/**
* 具体的抽象接口
*/
interface Target {
int outPut22V();
}
/**
* 适配器类
*/
@AllArgsConstructor
class Adapter implements Target{
private Adaptee adaptee;
@Override
public int outPut22V() {
int i = adaptee.outPut220V();
// 2.适配转换操作
int result = i / 10;
// 返回适配后结果
return result;
}
}
/**
* 客户端类
*/
class Phone{
public void charging(Target target) {
// 得到期望结果,开始后续操作
int i = target.outPut22V();
System.out.println("当前电压为"+i+"开始充电操作");
}
}
public class AdapterMode{
public static void main(String[] args) {
Phone phone = new Phone();
phone.charging(new Adapter(new Adaptee()));
}
}
参考链接
死磕设计模式—适配器模式