设计模式之【适配器模式】

发布于:2024-06-28 ⋅ 阅读:(18) ⋅ 点赞:(0)

类适配器实现(继承)

类适配器通过继承来实现适配器功能

// 目标接口
public interface Target {
    void request();
}

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

// 适配器
public class Adapter extends Adaptee implements Target {
    /**
     * 采用继承的方式实现转换功能
     */
    @Override
    public void request() {
        super.specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}

对象适配器实现(组合)

对象适配器通过组合来实现适配器功能

// 目标接口
public interface Target {
    void request();
}

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

// 适配器
public class Adapter implements Target {
    private Adaptee adaptee;

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

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

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}