一、应用场景
1、已存在的类,它的方法和需求不匹配的情况;
2、适配器模式不是软件设计阶段考虑的设计模式,是随着软件维护,由于不同产品、不同厂家造成功能类似而接口不相同情况下的解决方案;
二、适配器模式
将一个类的接口转化成客户端希望的目标类格式,使得原本不兼容的类可以在一起工作。
图 适配器说明
2.1 分类
2.1.1 类的适配器模式
图 类的适配器
/**
* typeC插槽[目标类]
*/
public interface TypeCSlot {
void runApplet();
}
/**
* Usb 插头 【需适配的类】
*/
public class UsbPlug {
void specialRun() {
System.out.println("USB插头专属功能");
}
}
/**
* 第三方适配器
*/
public class ThirdAdapter extends UsbPlug implements TypeCSlot{
@Override
public void runApplet() {
System.out.println("适配器操作");
super.specialRun();
}
}
public class Macbook {
public static void main(String[] args) {
System.out.println("Macbook 使用的是TypeC 接口,但是有个需求需要读取USB内容:");
ThirdAdapter thirdAdapter = new ThirdAdapter();
thirdAdapter.runApplet();
}
}
图 类的适配器运行结果
2.1.2 对象的适配器模式
图 对象的适配器
/**
* RSA 加密接口
*/
public interface RSAEncryption {
void encrypt(String str);
}
/**
* 系统原先编写的RSA加密类
*/
public class RSAOrgEncryption {
public void encryptValue(String str) {
System.out.println("RSA加密:" + str);
}
}
/**
* RSA 适配器
*/
public class RSAAdapter implements RSAEncryption{
private RSAOrgEncryption rsaOrgEncryption;
public RSAAdapter(RSAOrgEncryption rsaOrgEncryption) {
this.rsaOrgEncryption = rsaOrgEncryption;
}
@Override
public void encrypt(String str) {
System.out.println("适配器操作");
rsaOrgEncryption.encryptValue(str);
}
}
public class RSATest {
public static void main(String[] args) {
RSAOrgEncryption orgEncryption = new RSAOrgEncryption();
RSAAdapter rsaAdapter = new RSAAdapter(orgEncryption);
rsaAdapter.encrypt("123456");
}
}
2.1.3 接口的适配器模式
一个接口中有多个抽象方法,但并不是所有方法我们都需要的,引入适配器模式,借助一个抽象类,该抽象类实现了该接口所有方法,然后新类继承该抽象类,重写我们需要的方法。
图 接口的适配器模式
/**
* 电脑接口
*/
public interface Computer {
void readBook();
void writeCode();
void playGames();
}
/**
* 电脑抽象类
*/
public abstract class ComputerAbstract implements Computer{
@Override
public void readBook() {}
@Override
public abstract void writeCode();
@Override
public void playGames() {}
}
public class Macbook extends ComputerAbstract{
@Override
public void writeCode() {
System.out.println("程序员最喜欢的电脑之一");
System.out.println("屏幕特别好,系统特别流畅");
}
public static void main(String[] args) {
Computer macbook = new Macbook();
macbook.writeCode();
}
}
图 接口的适配器运行结果
三 优缺点
优点:
1)将目标类与适配类解耦;
2)增加了类的透明性和复用性,将具体实现封装在适配者类中,对于客户端来说是透明的;
缺点:
1)过多使用适配器,会让系统非常凌乱,不易整体进行把握;