【设计模式07】适配器

发布于:2025-07-04 ⋅ 阅读:(12) ⋅ 点赞:(0)

前言

实现目标,组合源,写个适配方法,适用于没办法改变源,但又想实现目标类。我暂时还没使用到过,但感觉用处还是蛮大的

UML类图

在这里插入图片描述

代码示例



package com.sw.learn.pattern.C_structre.a_adapter;

public class Main {
    // 目标5v,接口表示提供了获取5v的能力
    interface FiveVolt {
        int get5Volt();
    }

    // 源(被适配类),继承表示提供获取220v的能力
    static class PowerSource220V {
        public int get220Volt() {
            return 220;
        }
    }

    // 源2(被适配类),继承表示提供获取110v的能力
    static class PowerSource110V {
        public int get110Volt() {
            return 110;
        }
    }

    // Adapter适配器: 充电器,把 220V 转为 5V
    static class VoltageAdapter extends PowerSource220V implements FiveVolt {
        @Override
        public int get5Volt() {
            int original = this.get220Volt();
            return original / 44; // 简化模拟变压过程
        }
    }

    // Adapter适配器: 充电器,把 110V 转为 5V
    static class VoltageAdapter2 implements FiveVolt {
        private PowerSource110V powerSource110V;

        // 组合代替继承
        public VoltageAdapter2() {
            this.powerSource110V = new PowerSource110V();
        }

        @Override
        public int get5Volt() {
            int original = powerSource110V.get110Volt();
            return original / 22; // 简化模拟变压过程
        }
    }

    // Client: 手机
    static class Phone {
        public void charge(FiveVolt power) {
            System.out.println("正在使用 " + power.get5Volt() + "V 电压充电");
        }
    }


    public static void main(String[] args) {
        Phone phone = new Phone();
        FiveVolt adapter = new VoltageAdapter();
        phone.charge(adapter);

        FiveVolt adapter2 = new VoltageAdapter2();
        phone.charge(adapter2);
    }
}