适配器模式(Adapter)
适配器模式是构造型模式之一,通过适配器模式可以改变已有类(或外部类)的接口形式
1. 适配器模式中的角色及其职责
1.1 目标接口
客户端使用的接口
Target
package com.liuyao;
/**
* @author liuyao
* @date 2018/08/03
*/
public interface Target {
public void use18V();
}
1.2 被适配者
需要被适配的对象
Resident
package com.liuyao;
/**
* @author liuyao
* @date 2018/08/03
*/
public class Resident {
public void use220V(){
System.out.println("居民使用220V电");
}
}
1.3 适配器
将被适配者转换为目标接口
Adapter(继承方式)
package com.liuyao;
/**
* @author liuyao
* @date 2018/08/03
*/
public class Adapter extends Resident implements Target {
@Override
public void use18V(){
super.use220V();
System.out.println("使用适配器转换");
}
}
Adapter2(通过组合方式)
package com.liuyao;
/**
* @author liuyao
* @date 2018/08/03
*/
public class Adapter2 implements Target {
Resident resident;
public Adapter2(Resident resident) {
this.resident = resident;
}
@Override
public void use18V() {
resident.use220V();
System.out.println("使用适配器转换");
}
}
采用继承方式
采用组合方式
Main
package com.liuyao;
public class Main {
public static void main(String[] args) {
Adapter adapter=new Adapter();
adapter.use18V();
Resident resident=new Resident();
Adapter2 adapter2=new Adapter2(resident);
adapter2.use18V();
}
}
//居民使用220V电
//使用适配器转换
//居民使用220V电
//使用适配器转换
2. 应用场景
大规模的系统开发过程中,我们需要实现某些功能,这些功能以及有还不太成熟的一个或多个外部条件。这个时候我们会使用适配器模式,通过顶一个一个新的接口(对要实现的功能加以抽象),和一个实现该接口的Adapter(适配器)来透明地调用外部组件。这样替换后面替换外部组件时,最多只需要修改几个Adapter就可以了,其他源码不会受影响。