适配器设计模式
1, 定义
将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
2, 特点
优点:
1、可以让任何两个没有关联的类一起运行。
2、提高了类的复用。
3、灵活性好。
3, 代码实战
下面通过代码看懂什么是适配器设计模式
3.1 接口 OnlineMethod, 用于定义上网方式
** * 模拟有多种上网方式: 3G,4G,5G * 这里使用空的默认方法来代表上面三种不同的上网方式 * 由每个不同的实现类分别实现这三种方法 */ public interface OnlineMethod { default void threeGeneration(){} default void fourGeneration(){} default void fiveGeneration(){}}
复制代码
3.2 接口 OnlineMethod 的三种实现类,
public class FiveGeneration implements OnlineMethod{ @Override public void fiveGeneration() { System.out.println("5G 上网: 无人驾驶控制无延迟..."); }}
复制代码
public class FourGeneration implements OnlineMethod{ @Override public void fourGeneration() { System.out.println("4G上网: 看剧没问题..."); }}
复制代码
public class ThreeGeneration implements OnlineMethod{ @Override public void threeGeneration() { System.out.println("3G 上网方式:聊天够用"); }}
复制代码
3.3 接口 SurfInternet, 用于定义一种功能
/** * 代表模拟上网的功能: onLine * 参数代表: 控制使用什么方式, 后台根据不同的控制标识符(String类型的method)来选择使用不同的实现类 */public interface SurfInternet { void onLine(String method);}
复制代码
3.4 需求: 对外提供一种统一方法, 使用 OnlineMethod 的多种实现类, 这里就可以使用适配器来实现
public class SurfInternetAdapter implements SurfInternet { private OnlineMethod onlineMethod; //这里使用一种方法, 内部根据参数不同, 来使用使用OnlineMethod的不同实例来工作. @Override public void onLine(String method) { if ("3G".equals(method)) { onlineMethod = new ThreeGeneration(); onlineMethod.threeGeneration(); } else if ("4G".equals(method)) { onlineMethod = new FourGeneration(); onlineMethod.fourGeneration(); } else if ("5G".equals(method)) { onlineMethod = new FiveGeneration(); onlineMethod.fiveGeneration(); } }}
复制代码
3.5 测试类
public class MainJob { public static void main(String[] args) { SurfInternet surfInternet = new SurfInternetAdapter(); /** * 切换使用三种不同的实现类 */ surfInternet.onLine("3G"); surfInternet.onLine("4G"); surfInternet.onLine("5G"); }}
复制代码
结果输出:
3G 上网方式:聊天够用4G上网: 看剧没问题...5G 上网: 无人驾驶控制无延迟...
复制代码
总结: 适配器设计模式的本质很简单, 用一个被称为适配器的类, 来根据不同的逻辑, 选择由哪个类的实例干活.
评论 (1 条评论)