• java 实现适配器模式


    适配器模式(Adapter Pattern)是一种结构型设计模式,用于将一个类的接口转换成另一个类的接口,使得原本不兼容的类可以协同工作。适配器模式包括两种类型:类适配器和对象适配器。下面分别介绍这两种类型的实现方式。

    类适配器模式

    类适配器模式使用继承来实现适配器。在这种模式下,适配器类继承了需要适配的类,并实现了目标接口。以下是一个示例:

    首先,定义目标接口 Target

    public interface Target {
        void request();
    }
    
    • 1
    • 2
    • 3

    然后,定义需要适配的类 Adaptee

    public class Adaptee {
        public void specificRequest() {
            System.out.println("Adaptee's specific request");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    接下来,创建一个适配器类 ClassAdapter,它继承了 Adaptee 类并实现了 Target 接口:

    public class ClassAdapter extends Adaptee implements Target {
        @Override
        public void request() {
            specificRequest(); // 调用Adaptee的方法
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    现在,我们可以使用 ClassAdapter 类来将 Adaptee 类的接口转换成 Target 接口:

    public class AdapterPatternDemo {
        public static void main(String[] args) {
            Target target = new ClassAdapter();
            target.request(); // 调用Target接口的方法
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    对象适配器模式

    对象适配器模式使用组合来实现适配器。在这种模式下,适配器类持有一个需要适配的对象,并实现了目标接口。以下是一个示例:

    首先,定义目标接口 Target(与类适配器中相同):

    public interface Target {
        void request();
    }
    
    • 1
    • 2
    • 3

    然后,定义需要适配的类 Adaptee(与类适配器中相同):

    public class Adaptee {
        public void specificRequest() {
            System.out.println("Adaptee's specific request");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    接下来,创建一个适配器类 ObjectAdapter,它持有一个 Adaptee 对象并实现了 Target 接口:

    public class ObjectAdapter implements Target {
        private Adaptee adaptee;
    
        public ObjectAdapter(Adaptee adaptee) {
            this.adaptee = adaptee;
        }
    
        @Override
        public void request() {
            adaptee.specificRequest(); // 调用Adaptee的方法
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    现在,我们可以使用 ObjectAdapter 类来将 Adaptee 类的接口转换成 Target 接口:

    public class AdapterPatternDemo {
        public static void main(String[] args) {
            Adaptee adaptee = new Adaptee();
            Target target = new ObjectAdapter(adaptee);
            target.request(); // 调用Target接口的方法
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    无论是类适配器还是对象适配器,适配器模式都允许我们在不修改现有类的情况下实现接口的适配,以满足系统的需求。选择哪种模式取决于项目需求和设计偏好。

  • 相关阅读:
    进程相关知识总结
    通过LiveGo学习WebSocket
    【Linux】基本指令-入门级文件操作(二)
    设计模式之简单工厂模式(学习笔记)
    YOLO V1学习笔记
    省钱兄短视频小程序为何会大力扶持?
    操作失败——后端
    贝壳找房基于Flink+Paimon进行全量数据实时分组排序的实践
    springboot集成quartz并实现定时任务管理
    周报/月报 Prompt
  • 原文地址:https://blog.csdn.net/sunyuhua_keyboard/article/details/132672511