Please wait...

小波Note

四川 · 成都市多云14 ℃
English

Java Adapter

成都Mon, August 26, 2024 at 6 PM99530Estimated reading time 1 min
QR code
FavoriteCtrl + D

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

    
Astral