设计模式简单讲 - 适配器设计模式

适配器设计模式

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");
    }
}

结果输出:

扫描二维码关注公众号,回复: 13291563 查看本文章
3G 上网方式:聊天够用
4G上网: 看剧没问题...
5G 上网: 无人驾驶控制无延迟...

总结: 适配器设计模式的本质很简单, 用一个被称为适配器的类, 来根据不同的逻辑, 选择由哪个类的实例干活.

猜你喜欢

转载自blog.csdn.net/malipku/article/details/113446232