设计目的: 使旧接口兼容新接口,不改或少改原业务代码
使用场景: 公司系统框架上有一个接口A,程序员为了实现业务,创建一个实现了接口A的类并且在业务代码上大量使用接口A提供的方法。过了几个月,公司由于某种原因,要求放弃旧接口A,改用新接口B,但是旧接口A的实现类已经被大量使用在业务代码了,直接实现接口B需要修改大量代码,很容易造成大面积的bug。
使用适配器模式解决上述问题
类图
白话描述:把接口B“塞到”实现了A接口的具体类ImplA(建立关联关系)。通过ImplA的方法,调用接口B对应的方法。打个比方,在ImplA的send()方法里,调用InterfaceB的sendMsg()。这样的话原业务代码就不需要进行过多的改动。
代码
//旧接口A
public interface InterfaceA {
public void send();
public void receive();
public void close();
}
//实现类ImplA
public class ImplA implements InterfaceA {
InterfaceB implB;
//构造代码块,创建ImplA实例时就会执行
{
implB = new ImplB();
}
@Override
public void send() {
implB.sendMsg();//删除了原本send()的实现代码,改为调用implB.sendMsg的方法
}
@Override
public void receive() {
implB.receiveMsg();
}
@Override
public void close() {
implB.closeMsg();
}
}
//新接口B
public interface InterfaceB {
public void sendMsg();
public void receiveMsg();
public void closeMsg();
public void other();
}
//实现类ImplB
public class ImplB implements InterfaceB {
@Override
public void sendMsg() {
System.out.println("this is a new interface send method");
}
@Override
public void receiveMsg() {
System.out.println("this is a new interface receive method");
}
@Override
public void closeMsg() {
System.out.println("this is a new interface close method");
}
@Override
public void other() {
System.out.println("this is a new interface method");
}
}
//原业务代码,真正的项目可能会有上千个地方使用这段代码
public class Main {
public static void main(String[] args) {
InterfaceA implA = new ImplA();
implA.send();
implA.receive();
implA.close();
}
}
输出结果:
this is a new interface send method
this is a new interface receive method
this is a new interface close method
看代码可以很容易理解,旧接口A里面的方法直接调用新接口的方法,业务代码基本不需要变动。
同时,也体验了面向对象的特点——封装。使用者(业务代码)不需要关心对象内部代码如何实现。
另外,值得一提的是,旧接口可以传入N个新接口,implB、implC。。。然后在实现方法中组合使用。当然这样在设计上看起来有点像“策略模式”,但没关系它仍然算是适配器模式。
23种设计模式只是前人在面向接口的设计思想的总结,说白了只是常用于 设计 “高内聚,低耦合”系统的经验。
学习设计模式的目的是把“六大原则”融汇贯通。