设计模式-适配器模式

适配器模式概念

适配器模式(Adapter Pattern)属于结构型设计模式,它的作用是将一个类的接口转换成客户希望的另外一个接口。适配器让原本由于接口不兼容而不能一起工作的类可以协同工作。

适配器模式包括三个角色:目标抽象类(Target)、适配器类(Adapter)和被适配者类(Adaptee)。

  • 目标抽象类(Target):定义了客户端使用的与特定领域相关的接口,也就是客户端需要的方法。
  • 适配器类(Adapter):通过继承或者组合方式,将被适配者类的接口与目标抽象类的接口转换起来,使得客户端可以按照目标抽象类的接口进行操作。
  • 被适配者类(Adaptee):已经存在的、功能稳定的类,在这里指的是需要适配的类。

适配器模式主要分为类适配器模式和对象适配器模式两种实现方式:

  • 类适配器模式:通过继承来实现适配器功能;
  • 对象适配器模式:通过组合来实现适配器功能。

适配器模式在实际开发中非常常见,比如我们经常需要连接各种不同的数据库,每种数据库都有自己独特的接口和方法。如果我们希望写出一段通用的代码,能够连接到任何一种数据库并执行相同的操作,那么适配器模式就非常适合解决这个问题。

接口Target

java 复制代码
package com.cocoa.adapter;

public interface Target {
    void request();
}

类TargetImpl

java 复制代码
package com.cocoa.adapter;

public class TargetImpl implements Target {
    @Override
    public void request() {
        System.out.println("TargetImpl 的 request 方法被调用");
    }
}

类TargetClass

类src适配后,可以调用TargetClass的方法(也就是完成了适配)

java 复制代码
package com.cocoa.adapter;

public class TargetClass {
    public void print(){
        System.out.println("TargetClass print 被执行");
    }
}

接口Src

java 复制代码
package com.cocoa.adapter;

public interface Src {
    void specificRequest();
}

类SrcImpl

java 复制代码
package com.cocoa.adapter;

public class SrcImpl implements Src {
    @Override
    public void specificRequest() {
        System.out.println("SrcImpl 的 specificRequest 方法被调用");
    }
}

类Adapter(适配器类)

通过组合的方式,将src适配为Target

java 复制代码
package com.cocoa.adapter;

public class Adapter extends TargetClass implements Target {
    private Src adaptee;// 组合

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

    @Override
    public void request() {
        this.print();// 调用适配后的方法

        adaptee.specificRequest();// 调用被适配者的方法
    }
}

测试类Main

java 复制代码
package com.cocoa.adapter;

public class Main {
    public static void main(String[] args) {
        Src adaptee = new SrcImpl();
        Target target = new Adapter(adaptee);

        target.request();
    }
}
相关推荐
怕浪猫16 分钟前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher2 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
咖啡八杯3 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong3 天前
学习创建结构行为设计模式
设计模式
w_t_y_y3 天前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式
zhouhui0013 天前
订单状态的 if-else 地狱上线就崩——状态模式的工业级落地
设计模式
geovindu3 天前
go: Reactor Pattern
开发语言·后端·设计模式·golang·反应器模式
一只旭宝4 天前
【C++入门精讲22】常见设计模式
c++·设计模式
许彰午4 天前
38_Java设计模式之装饰器模式
java·设计模式·装饰器模式