当前位置: 首页 > 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;@Overridepublic boolean isOn() { return isOn; }@Overridepublic void powerOn() {isOn = true;System.out.println("电视机已启动,欢迎使用");}@Overridepublic void powerOff() {isOn = false;System.out.println("电视机已关闭");}@Overridepublic void setVolume(int volume) {this.volume = Math.min(100, Math.max(0, volume));System.out.println("电视机音量设置:" + this.volume);}@Overridepublic int getVolume() { return volume; }
}

设备2:空调实现

public class Radio implements Device {private boolean isOn = false;private int volume = 30;@Overridepublic boolean isOn() { return isOn; }@Overridepublic void powerOn() {isOn = true;System.out.println("收音机启动,开始播放广播");}@Overridepublic void powerOff() {isOn = false;System.out.println("收音机已关闭");}@Overridepublic void setVolume(int volume) {this.volume = Math.min(50, Math.max(0, volume)); // 收音机音量上限较低System.out.println("收音机音量设置:" + this.volume);}@Overridepublic 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);}@Overridepublic void power() {if (device.isOn()) {device.powerOff();} else {device.powerOn();}}@Overridepublic void volumeUp() {device.setVolume(device.getVolume() + 5);}@Overridepublic 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;}@Overridepublic void display(int indent) {String space = "  ".repeat(indent);System.out.println(space + "📦 " + name + " ¥" + price);}@Overridepublic 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);}@Overridepublic void display(int indent) {String space = "  ".repeat(indent);System.out.println(space + "📁 " + categoryName);for (CatalogComponent item : items) {item.display(indent + 1); // 递归调用}}@Overridepublic 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 {@Overridepublic String getDescription() {return "🗡️ 铁剑";}@Overridepublic int getAttackPower() {return 10;}
}

3.装饰器基类

public abstract class WeaponDecorator implements Weapon {protected Weapon decoratedWeapon;public WeaponDecorator(Weapon weapon) {this.decoratedWeapon = weapon;}@Overridepublic String getDescription() {return decoratedWeapon.getDescription();}@Overridepublic int getAttackPower() {return decoratedWeapon.getAttackPower();}
}

4.具体装饰器

装饰器1:

public class FireEnchant extends WeaponDecorator {public FireEnchant(Weapon weapon) {super(weapon);}@Overridepublic String getDescription() {return super.getDescription() + " 🔥火焰附魔";}@Overridepublic int getAttackPower() {return super.getAttackPower() + 5;}
}

装饰器2:

public class AttackBoost extends WeaponDecorator {public AttackBoost(Weapon weapon) {super(weapon);}@Overridepublic String getDescription() {return super.getDescription() + " ⚡攻击强化";}@Overridepublic 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 不同电器抽象类持有实现接口
组合模式统一处理树状结构商品分类嵌套递归调用 + 组件集合
装饰模式动态添加功能,无需修改原有代码游戏装备强化装饰器持有被装饰对象,链式调用

http://www.mrgr.cn/news/97733.html

相关文章:

  • Java BigInteger 详解
  • 蓝桥杯-小明的彩灯(Java-差分)
  • 【小沐杂货铺】基于Three.JS绘制太阳系Solar System(GIS 、WebGL、vue、react,提供全部源代码)
  • 刷题 | 牛客 - js简单10题(更ing)1/10知识点解答
  • 美团Leaf分布式ID生成器:雪花算法原理与应用
  • ·DCDC电源模块学习
  • 蓝桥杯-最大数目
  • SpringBoot和微服务学习记录Day1
  • MySQL介绍及使用
  • 【leetcode hot 100 118】杨辉三角
  • 蓝桥杯-蓝桥幼儿园(Java-并查集)
  • 【小沐杂货铺】基于Three.JS绘制三维数字地球Earth(GIS 、WebGL、vue、react,提供全部源代码)
  • 前端-项目工程化(快速理解并会用)
  • 前端知识点---闭包(javascript)
  • 使用MySQL时出现 Ignoring query to other database 错误
  • Dubbo 注册中心与服务发现
  • 基于SpringBoot的“线上考试系统”的设计与实现(源码+数据库+文档+PPT)
  • Spring Boot 常用依赖介绍
  • 瓦片数据合并方法
  • 【Python】Python 100题 分类入门练习题 - 新手友好