设计模式之适配器模式

概念:将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。

结构比较简单,有一个目标接口,需要将原始类的操作,通过适配器类转换成目标接口的操作。适配器类既要实现目标接口,也要继承原始类。这里我们来举一个变压器的例子。

java 复制代码
public interface Target {
    double getTargetVoltage();
}

public interface OriginalInterface {
    double getVoltage();
}

public class Original implements OriginalInterface {
    @Override
    public double getVoltage() {
        return 220;
    }
}

public class Adaptor implements Target {
    private OriginalInterface originalInterface;
    public Adaptor(OriginalInterface originalInterface) {
        this.originalInterface = originalInterface;
    }
    @Override
    public double getTargetVoltage() {
        return originalInterface.getVoltage() / 44;
    }
}

public class Demo {
    public static void main(String[] args) {
        Original originalInterface = new Original();
        Adaptor adaptor = new Adaptor(originalInterface);
        double targetVoltage = adaptor.getTargetVoltage();
        System.out.println("源电压: " + originalInterface.getVoltage());
        System.out.println("目标电压: " + targetVoltage);
    }
}

如果大家需要视频版本的讲解,可以关注我的B站:

九、设计模式之适配器模式精讲

相关推荐
博风8 小时前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶9 小时前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
geovindu14 小时前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
拆房老料15 小时前
【第四部分:Agentic 智能体设计模式】15.为什么 Agent 也需要设计模式
人工智能·设计模式·ai·ai-native
geovindu16 小时前
rust: Chain of Responsibility Pattern (续)
开发语言·后端·设计模式·rust·责任链模式·行为模式
Lost of 程序猿16 小时前
责任链模式实战:审批流里“层层把关“的艺术
后端·设计模式·asp.net·责任链模式
希洛兔1 天前
状态模式详解:让对象随内部状态自动改变行为
java·设计模式·状态模式
博风1 天前
7、设计模式应用举例:策略模式:加密、解密文件
设计模式·策略模式
4SAPI1 天前
Provider Adapter设计模式:如何让AI应用支持多个模型
网络·人工智能·设计模式
geovindu2 天前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式