设计模式之适配器(adapter)模式 -- 适配老版本接口和第三方接口
场景介绍:
(1)假设我们做了一个第一版的一个系统,这个系统里有一个接口和一个实现类
(2)接着我们开始做第二版的系统,这个系统我们定义了一个新的接口,和新的实现类
(3)但是我们同时在第二版的系统中,也要使用第一版系统中定义的那个老接口和老实现类
1.不使用设计模式的实现方式如下:
package com.lucky.pattern.adapter;
/**
* @author: LIJY
* @Description: 不使用设计模式的实现
* @Date: 2021/10/1 17:58
*/
public class WithoutAdapterPatternDemo {
public static void main(String[] args) {
OldInterface oldInterface = new OldInterfaceImpl();
NewInterface newInterface = new NewInterfaceImpl();
oldInterface.oldExecute();
newInterface.newExecute();
}
/**
* 老版本的接口
*/
public static interface OldInterface {
void oldExecute();
}
/**
* 老版本的接口实现类
*/
public static class OldInterfaceImpl implements OldInterface {
public void oldExecute() {
System.out.println("老版本接口实现的功能逻辑");
}
}
/**
* 新版本的接口
*/
public static interface NewInterface {
void newExecute();
}
/**
* 新版本的接口实现类
*/
public static class NewInterfaceImpl implements NewInterface {
public void newExecute() {
System.out.println("新版本接口实现的功能逻辑");
}
}
}
不适用设计模式的缺点和问题:
在调用接口的代码中,融合和新旧两套接口,这是一件很麻烦的事。
- 新旧接口面向的规范和风格是完全不同的两套接口时,理解和维护的成本就提高了;
- 可能不给你在新的项目中使用老接口的机会,强制要求按照新版本的接口走,老接口的实现类就没法使用了。
2.使用设计模式的实现方式如下:
package com.lucky.pattern.adapter;
/**
* @author: LIJY
* @Description: 使用适配器设计模式的实现
* @Date: 2021/10/1 22:11
*/
public class AdapterPatternDemo {
public static void main(String[] args) {
NewInterface oldObject = new NewInterfaceAdapter(new OldInterfaceImpl());
NewInterface newObject = new NewInterfaceImpl();
oldObject.newExecute();
newObject.newExecute();
}
/**
* 定义一个适配器类
*/
public static class NewInterfaceAdapter implements NewInterface {
private OldInterface oldObject;
public NewInterfaceAdapter(OldInterface oldObject) {
this.oldObject = oldObject;
}
public void newExecute() {
oldObject.oldExecute();
}
}
/**
* 老版本的接口
*/
public static interface OldInterface {
void oldExecute();
}
/**
* 老版本的接口实现类
*/
public static class OldInterfaceImpl implements OldInterface {
public void oldExecute() {
System.out.println("老版本接口实现的功能逻辑");
}
}
/**
* 新版本的接口
*/
public static interface NewInterface {
void newExecute();
}
/**
* 新版本的接口实现类
*/
public static class NewInterfaceImpl implements NewInterface {
public void newExecute() {
System.out.println("新版本接口实现的功能逻辑");
}
}
}
3. 适配器模式:
有新老两个接口和新老接口的实现类,现在项目中要面向新接口开发,老接口的实现类就不能直接用了,不能直接面向老接口开发。
解决方法:
开发一个老接口到新接口的适配器,适配器是实现了新接口的,但是适配器中持有老接口实现类实例的引用,适配器的新接口方法的实现,全部是基于老接口实现类的方法来实现即可。
对于调用法而言,只要使用适配器来开发即可,就可以通过面向新接口开发,底层使用老接口实现类。