当前位置: 首页 > news >正文

设计模式之桥接、组合、装饰模式

一、桥接模式

1.所有电器的通用插座:

// bridge/device/Device.java
public interface Device {
// 所有电器必须实现的功能
    boolean isOn();
    void powerOn();
    void powerOff();
    void setVolume(int volume);
    int getVolume();
}

2.具体设备实现

设备1:电视实现

public class TV implements Device {
    private boolean isOn = false;
    private int volume = 50;

    @Override
    public boolean isOn() { return isOn; }

    @Override
    public void powerOn() {
        isOn = true;
        System.out.println("电视机已启动,欢迎使用");
    }

    @Override
    public void powerOff() {
        isOn = false;
        System.out.println("电视机已关闭");
    }

    @Override
    public void setVolume(int volume) {
        this.volume = Math.min(100, Math.max(0, volume));
        System.out.println("电视机音量设置:" + this.volume);
    }

    @Override
    public int getVolume() { return volume; }
}

设备2:空调实现

public class Radio implements Device {
    private boolean isOn = false;
    private int volume = 30;

    @Override
    public boolean isOn() { return isOn; }

    @Override
    public void powerOn() {
        isOn = true;
        System.out.println("收音机启动,开始播放广播");
    }

    @Override
    public void powerOff() {
        isOn = false;
        System.out.println("收音机已关闭");
    }

    @Override
    public void setVolume(int volume) {
        this.volume = Math.min(50, Math.max(0, volume)); // 收音机音量上限较低
        System.out.println("收音机音量设置:" + this.volume);
    }

    @Override
    public int getVolume() { return volume; }
}

3.遥控器抽象层

父类(模板):

public abstract class RemoteControl {
    protected Device device; // 关键:持有一个设备

    public RemoteControl(Device device) {
        this.device = device;
    }

    public abstract void power();
    public abstract void volumeUp();
    public abstract void volumeDown();
}

子类

public class BasicRemote extends RemoteControl {
    public BasicRemote(Device device) {
        super(device);
    }

    @Override
    public void power() {
        if (device.isOn()) {
            device.powerOff();
        } else {
            device.powerOn();
        }
    }

    @Override
    public void volumeUp() {
        device.setVolume(device.getVolume() + 5);
    }

    @Override
    public void volumeDown() {
        device.setVolume(device.getVolume() - 5);
    }
}

4.测试类

public class Main {
    public static void main(String[] args) {
        // 测试电视机
        Device tv = new TV();
        RemoteControl tvRemote = new BasicRemote(tv);
        tvRemote.power();      // 开机
        tvRemote.volumeUp();   // 55
        
        // 测试收音机
        Device radio = new Radio();
        RemoteControl radioRemote = new BasicRemote(radio);
        radioRemote.power();    // 开机
        radioRemote.volumeUp();  // 35
    }
}

二、组件模式

1.所有物品的必需功能

public interface CatalogComponent {
    void display(int indent); // 缩进展示
    double calculatePrice(); // 计算总价
}

2.商品类

public class Product implements CatalogComponent {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public void display(int indent) {
        String space = "  ".repeat(indent);
        System.out.println(space + "📦 " + name + " ¥" + price);
    }

    @Override
    public double calculatePrice() {
        return price;
    }
}

3.商品分类

public class ProductCategory implements CatalogComponent {
    private String categoryName;
    private List<CatalogComponent> items = new ArrayList<>();

    public ProductCategory(String name) {
        this.categoryName = name;
    }

    public void addItem(CatalogComponent item) {
        items.add(item);
    }

    @Override
    public void display(int indent) {
        String space = "  ".repeat(indent);
        System.out.println(space + "📁 " + categoryName);
        for (CatalogComponent item : items) {
            item.display(indent + 1); // 递归调用
        }
    }

    @Override
    public double calculatePrice() {
        return items.stream()
                   .mapToDouble(CatalogComponent::calculatePrice)
                   .sum();
    }
}

4.测试类

public class Main {
    public static void main(String[] args) {
        CatalogComponent electronics = new ProductCategory("电子产品");
        electronics.addItem(new Product("iPhone", 5999));
        electronics.addItem(new Product("耳机", 399));

        electronics.display(0);
        System.out.println("总价值: ¥" + electronics.calculatePrice());
    }
}

三、装饰模式

1.武器接口

public interface Weapon {
    String getDescription();
    int getAttackPower();
}

2.基础武器实现

public class Sword implements Weapon {
    @Override
    public String getDescription() {
        return "🗡️ 铁剑";
    }

    @Override
    public int getAttackPower() {
        return 10;
    }
}

3.装饰器基类

public abstract class WeaponDecorator implements Weapon {
    protected Weapon decoratedWeapon;

    public WeaponDecorator(Weapon weapon) {
        this.decoratedWeapon = weapon;
    }

    @Override
    public String getDescription() {
        return decoratedWeapon.getDescription();
    }

    @Override
    public int getAttackPower() {
        return decoratedWeapon.getAttackPower();
    }
}

4.具体装饰器

装饰器1:

public class FireEnchant extends WeaponDecorator {
    public FireEnchant(Weapon weapon) {
        super(weapon);
    }

    @Override
    public String getDescription() {
        return super.getDescription() + " 🔥火焰附魔";
    }

    @Override
    public int getAttackPower() {
        return super.getAttackPower() + 5;
    }
}

装饰器2:

public class AttackBoost extends WeaponDecorator {
    public AttackBoost(Weapon weapon) {
        super(weapon);
    }

    @Override
    public String getDescription() {
        return super.getDescription() + " ⚡攻击强化";
    }

    @Override
    public int getAttackPower() {
        return super.getAttackPower() + 8;
    }
}

5.测试类

public class Main {
    public static void main(String[] args) {
        Weapon weapon = new Sword();
        weapon = new FireEnchant(weapon);
        weapon = new AttackBoost(weapon);

        System.out.println(weapon.getDescription()); 
        // 输出:🗡️ 铁剑 🔥火焰附魔 ⚡攻击强化
        System.out.println("攻击力: " + weapon.getAttackPower()); // 23
    }
}

关键点总结

模式核心思想类比场景代码特征
桥接模式抽象与实现解耦遥控器 vs 不同电器抽象类持有实现接口
组合模式统一处理树状结构商品分类嵌套递归调用 + 组件集合
装饰模式动态添加功能,无需修改原有代码游戏装备强化装饰器持有被装饰对象,链式调用

相关文章:

  • 深度学习 Deep Learning 第20章 深度生成模型
  • Java 面试系列:深入了解 Java 中的异常处理 + 面试题
  • react 中将生成二维码保存到相册
  • 实现usb的MTP功能
  • Springboot切换到3.3.4后,使用spring security一些小问题记录
  • 【基于Vue3组合式API的互斥输入模式实现与实践分享】
  • milvus向量数据库客户端安装,attu客户端安装
  • Excel 导入数据到GridControl中的方法
  • C++ - 头文件基础(常用标准库头文件、自定义头文件、头文件引入方式、防止头文件重复包含机制)
  • 多模态大语言模型arxiv论文略读(六)
  • 计算机视觉——为什么 mAP 是目标检测的黄金标准
  • c# 企业级ADB通信示例
  • 使用 new EventSource 实现前端实时通信
  • 数智化重构供应商管理
  • Java大视界:解码航天遥测数据的银河密码——从GB到PB的技术革命
  • Dubbo 注册中心与服务发现
  • 健身管理小程序|基于java微信开发健身管理小程序的系统设计与实现(源码+数据库+文档)
  • Web框架 --- Web服务器和Web应用服务器
  • Baumer工业相机堡盟工业相机如何处理偶发十万分之一或百万分之一几率出现的黑图现象(C#)
  • R语言之mlr依赖包缺失警告之分析
  • dw个人网站制作教程/seo推广关键词公司
  • 网站地址格式/如何做免费网站推广
  • 百度浏览器网址/搜索关键词优化服务
  • 做微信公众平台的网站吗/软文文章
  • 免费的app推广平台/搜索引擎优化seo
  • python兼职网站开发/互联网推广怎么找客户