Java设计模式之适配器模式(结构型模式)
定义:将一个类的接口转换成客户希望的另外一个接口。Adaptor模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
模式中的角色:
- 目标接口(Target):客户所期望的接口。目标可以是具体的或抽象的类,也可以是接口;
- 需要适配的类(Adaptee):需要适配的类或适配者类;
- 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
场景描述:现在很多的手机厂商都取消了3.5mm耳机接口,改为了TypeC接口。因此,若我们想将3.5mm的耳机插头插入手机的TypeC接口,则另外需要一个TypeC转换器。如图:
TypeC一端连接耳机后,就具有了耳机的功能(能够听歌),并且满足了TypeC插头的要求。
类适配器模式:
public class test {
public static void main(String[] args) {
Target adapter = new Adapter();
adapter.TypeC();
adapter.function();
}
}
Adaptee:耳机,能够听歌,但其3.5mm耳机插头与手机的TypeC接口不匹配
class EarPhone{
public void func() {
System.out.println("能够听歌!");
}
public String plugType() {
return "3.5mm耳机插头";
}
}
//Target:将耳机的3.5mm插头转换为TypeC插头
interface Target{
void TypeC();
void function();
}
//Adapter:适配器继承EarPhone后具有了耳机的功能,同时提供了TypeC插头
class Adapter extends EarPhone implements Target{
public void function() {
super.func();
}
@Override
public void TypeC() {
System.out.println(super.plugType() + "=>TypeC插头");
}
}
对象适配器模式:
public class test {
public static void main(String[] args) {
EarPhone earPhone= new EarPhone();
Target adapter2 = new Adapter2(earPhone);
adapter2.TypeC();
adapter2.function();
}
}
Adaptee:耳机,能够听歌,但其3.5mm耳机插头与手机的TypeC接口不匹配
class EarPhone{
public void func() {
System.out.println("能够听歌!");
}
public String plugType() {
return "3.5mm耳机插头";
}
}
//Target:将耳机的3.5mm插头转换为TypeC插头
interface Target{
void TypeC();
void function();
}
//Adapter:直接关联被适配类,同时实现标准接口
class Adapter2 implements Target{
private EarPhone earPhone;
public Adapter2(EarPhone earPhone) {
this.earPhone = earPhone;
}
@Override
public void TypeC() {
System.out.println(this.earPhone.plugType() + "=>TypeC接口");
}
@Override
public void function() {
this.earPhone.func();
}
}