1、适配器模式
适配器模式又被成为Adapter模式,它的主要作用是在新接口和老接口之间进行适配。适配器是一个比较常见的词语,比如我们的笔记本电源适配器。如果我们的电脑可能适配的电源是38V,但是我们的家用电源是220V的,这个时候就要用到电源适配器,做出一定的处理。
最典型的例子就是很多功能手机,每一种机型都自带有从电器,有一天自带充电器坏了,而且市场没有这类型充电器可买了。怎么办?万能充电器就可以解决。这个万能充电器就是适配器。
2、结构图示
适配器模式主要有两种结构,如下所示:
1)继承
2)委让
3、角色
这里也主要有三个角色:
Adaptee角色:这里主要是被适配的对象,这里它提供最原始的方法;
Adapter角色:适配器对象,提供新的方法,去适配当前的对象;
Client角色:客户端角色,它需要的东西,如果没有的话,就需要去找一个适配对象。
4、代码示例
两个Adapter类:
public class Adapter1 extends Current {
public void use18V() {
System.out.println("使用适配器");
this.use220V();
}
}
public class Adapter2 {
private Current current;
public Adapter2(Current current) {
this.current = current;
}
public void use18V() {
System.out.println("使用适配器");
this.current.use220V();
}
}
需要使用的对象:
public class Current {
public void use220V() {
System.out.println("使用220v电压");
}
}
测试:
public class MainClass {
public static void main(String[] args) {
Adapter1 adapter1 = new Adapter1();
adapter1.use18V();
System.out.println("-------------");
Adapter2 adapter2 = new Adapter2(new Current());
adapter2.use18V();
}
}
5、结果分析
结果:
使用适配器
使用220v电压
-------------
使用适配器
使用220v电压
分析:
我们使用了适配器之后,所有不同的电压都可以转换为当前需要的220V电压。Adapter2中,我们只需要指定当前需要适配的目标就可以了,比如这里我们就是去适配220V电压的对象。