适配器模式
Adapter模式也叫适配器模式,是构造型模式之一,通过Adapter模式可以改变已有类(或外部类)的接口形式。比如我们在使用笔记本电脑,它就有个电源适配器,笔记本工作电压只要20伏,而家电为220伏,两者不可以直接相连,则需要使用电源适配器
一、结构与角色
1.1 通过继承实现适配器
客户端调用的时候requiredMethod,而组件提供的是oldMethod,采用继承的方法实现适配器,适配器提供requiredMethod,里面其实调用了super.oldMethod
1.2 通过委让实现适配器
采用组合的方式,里面包含了被适配的引用,然后调用oldMethod方法
二、应用场景
我们需要实现某些功能,这些功能已有还不太成熟的一个或多个外部组件,如果我们自己重新开发这些功能会花费大量时间;所以很多情况下会选择先暂时使用外部组件,以后再考虑随时替换。但这样一来,会带来一个问题,随着对外部组件库的替换,可能需要对引用该外部组件的源代码进行大面积的修改,因此也极可能引入新的问题等等。
Adapter模式通过定义一个新的接口(对要实现的功能加以抽象),和一个实现该接口的Adapter(适配器)类来透明地调用外部组件。这样替换外部组件时,最多只要修改几个Adapter类就可以了,其他源代码都不会受到影响。
2.1 不使用适配器
例如组件不成熟的时候,我已经使用了Current去创建对象并使用,如果后期需要修改或者替换的话,则客户端使用的对象与调用则全部修改
//组件不成熟的时候
public class Current {
public void use220V(){
System.out.println("使用220V");
}
}
public class MainClass {
public static void main(String[] args){
//直接使用电线
Current current = new Current();
current.use220V();
}
}
2.2 使用适配器
例如组件不成熟的时候,我们使用适配器去调用Current这个组件,当组件需要修改或者替换的时候,我只需要修改适配器的父类方法或者是修改需要继承的类,但是use18V方法依旧存在,只是修改继承类或者this.use220V方法,所以客户端不需要修改代码,减少了修改面
public class Current {
public void use220V(){
System.out.println("使用220V");
}
}
public class Adapter extends Current{
public void use18V(){
System.out.println("使用适配器");
this.use220V();
}
}
public class MainClass {
public static void main(String[] args){
//使用适配器
Adapter adapter = new Adapter();
adapter.use18V();
}
}
三、使用继承实现适配器
3.1 Current
public class Current {
public void use220V(){
System.out.println("使用220V");
}
}
3.2 Adapter
public class Adapter extends Current{
public void use18V(){
System.out.println("使用适配器");
this.use220V();
}
}
3.3 MainClass
public class MainClass {
public static void main(String[] args){
//直接使用电线
Current current = new Current();
current.use220V();
//使用适配器
Adapter adapter = new Adapter();
adapter.use18V();
}
}
四、使用委让实现适配器
4.1 Current
public class Current {
public void use220V(){
System.out.println("使用220V");
}
}
4.2 Adapter2
public class Adapter2 {
private Current current;
public Adapter2(Current current){
this.current = current;
}
public void user18V(){
System.out.println("使用适配器");
this.current.use220V();
}
}
4.3 MainClass
public class MainClass {
public static void main(String[] args){
//使用适配器,继承实现
Adapter adapter = new Adapter();
adapter.use18V();
//使用适配器,委让实现
Adapter2 adapter2 = new Adapter2(new Current());
adapter2.user18V();
}
}