设计模式之桥接、组合、装饰模式
一、桥接模式
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 不同电器 | 抽象类持有实现接口 |
组合模式 | 统一处理树状结构 | 商品分类嵌套 | 递归调用 + 组件集合 |
装饰模式 | 动态添加功能,无需修改原有代码 | 游戏装备强化 | 装饰器持有被装饰对象,链式调用 |