我们在酒店里想给手机充电,我们手机充电器是110W的,但是酒店的电压是220W.这时就需要一个适配器,将电压转为适合我们手机的.
适配器模式定义:
适配器模式是一种结构型设计模式。适配器模式的思想是:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作
适配器模式涉及3个角色:
- 源(Adaptee):需要被适配的对象或类型,相当于插头。
- 适配器(Adapter):连接目标和源的中间对象,相当于插头转换器。
- 目标(Target):期待得到的目标,相当于插座。
适配器模式分为:
- 类适配器: 通过继承来实现接口适配
- 对象适配器: 通过对象组合方式来实现.
客户端使用适配器的模式如下:
- 客户通过目标接口调用适配器的方法对适配器发出请求
- 适配器使用被适配者接口吧请求转换成被适配者的一个或多个调用接口
- 客户接收到调用的结果,但并未察觉这一切是适配器在起转换的作用
类适配器类图
/**
* 目标接口 将110W转为220W
*/
public interface Target {
public void to220W();
}
/**
* 原始的110W
*/
public class Is110W {
public void is110W(){
System.out.println("110W");
}
}
/**
- 被适配类,实现Target接口
*/
public class Is220W implements Target {
@Override
public void to220W() {
System.out.println(“220W”);
}
}
/**
* 类适配器
*/
public class Adater extends Is110W implements Target {
@Override
public void to220W() {
super.is110W();
}
public static void main(String[] args) {
// 直接使用220W
final Target is110W = new Is220W();
is110W.to220W();
final Target adater = new Adater();
adater.to220W();
}
}
测试结果
对象适配类图
只是Adapter和类适配器不一样,对象适配器通过组合的方式.
/**
* 对象适配器,通过组合方式实现适配
*/
public class Adapter implements Target{
private Is110W is110W;
@Override
public void to220W() {
is110W.is110W();
}
public Adapter(Is110W is110W) {
this.is110W = is110W;
}
public static void main(String[] args) {
// 使用110W
final Target is220W = new Is220W();
is220W.to220W();
// 使用220W
final Adapter adapter = new Adapter(new Is110W());
adapter.to220W();
}
}
运行结果
应用场景:
当需要使用一个现有的类,但是接口并不符合我们的要求时,可以使用适配器来适配为我们需要的接口.