Please wait...

小波Note

四川 · 成都市11 ℃
English

Java Adapter

成都 (cheng du)8/26/2024, 6:10:23 PM995Estimated reading time 3 minFavoriteCtrl + D / ⌘ + D
cover
IT FB(up 主)
Back-end development engineer

The Adapter pattern is a structural design pattern that allows you to convert the interface of a class into another interface that the client expects. Adapter pattern lets classes work together that couldn't otherwise because of incompatible interfaces.

定义目标接口

java
        public interface Target {
    void request();
}

    

创建适配器类

java
        public class Adaptee {
    public void specificRequest() {
        System.out.println("Called specificRequest()");
    }
}

    

实现适配器类

java
        public class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

    

使用适配器模式

java
        public class AdapterPatternDemo {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);

        target.request();
    }
}