? ? ? 装饰模式(Decorator Pattern)是结构型的设计模式,它允许在运行时动态地向对象添加新的职责或功能,同时保持对象的原始类不变。通过使用装饰器模式,可以在不修改现有代码的基础上扩展对象的功能,遵循了开闭原则(Open-Closed Principle, OCP),对扩展开放和对修改封闭。
装饰模式示例代码如下:
// 抽象构件
public abstract class Coffee {
public abstract double getCost();
public abstract String getDescription();
}
// 具体构件
public class SimpleCoffee extends Coffee {
@Override
public double getCost() {
return 1.0;
}
@Override
public String getDescription() {
return "Simple Coffee";
}
}
// 装饰器抽象类
public abstract class CoffeeDecorator extends Coffee {
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public double getCost() {
return coffee.getCost();
}
@Override
public String getDescription() {
return coffee.getDescription();
}
}
// 具体装饰器
public class MilkCoffeeDecorator extends CoffeeDecorator {
public MilkCoffeeDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double getCost() {
return super.getCost() + 0.5; // 添加牛奶的价格
}
@Override
public String getDescription() {
return super.getDescription() + ", with Milk"; // 描述中增加牛奶信息
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Coffee simpleCoffee = new SimpleCoffee();
System.out.println("Cost: " + simpleCoffee.getCost());
System.out.println("Description: " + simpleCoffee.getDescription());
Coffee milkCoffee = new MilkCoffeeDecorator(simpleCoffee);
System.out.println("\nCost after adding milk: " + milkCoffee.getCost());
System.out.println("Description after adding milk: " + milkCoffee.getDescription());
}
}
?说明:上面的代码,Coffee
?是抽象构件,SimpleCoffee
?是具体构件。CoffeeDecorator
?是装饰器抽象类,而?MilkCoffeeDecorator
?是具体的装饰器类,它给咖啡增加了加奶的功能,并且相应地调整了成本和描述。通过这样的设计,我们可以很容易地添加其他类型的装饰器(例如糖、香草等),从而扩展咖啡的不同口味和价格。