装饰者模式

Definition: 装饰者模式动态地将责任附加到对象上。可以代替继承,利于扩展功能
遵循OCP原则的模式
 
使用装饰者类去「包装」被装饰类(组合 + 继承)
  • Decorater 和 Decoratee 都间接继承于同一个基类,保证包装过后对象的根本行为是不变的(无论怎么包装InputStream,本质都是InputStream)
  • Decorator可以在Decoratee的行为前后加上自己的行为
  • 动态装饰,不限量嵌套装饰
    • notion image
notion image
 
namespace DecoratorPattern; public abstract class Bevegar { private string description = String.Empty; public string GetDescription() { return description; } public abstract double cost(); } public abstract class CondimentDecorator : Bevegar { // 由于Decorator需要包装Bevegar并调用其方法 // 所以必须在具体子类中实现Bevegar的非抽象方法 public new abstract string GetDescription(); } public class Espresso : Bevegar{ public override double cost() { return 3.05; } } public class Mocha : CondimentDecorator { // 被装饰者类实例 private Bevegar bevegar; public Mocha(Bevegar bevegar) { this.bevegar = bevegar; } public override string GetDescription() { return bevegar.GetDescription() + ", Mocha"; } public override double cost() { return bevegar.cost() + 1.20; } }
实际运用:
namespace DecoratorPattern; class DecoratorPatternDemo { static void Main() { Bevegar espresso = new Espresso(); Console.WriteLine($"Single Espresso: {espresso.cost()}"); Bevegar espressoWithOneMocha = new Mocha(espresso); Console.WriteLine($"Espresso with one mocha: {espressoWithOneMocha.cost()}"); Bevegar espressoWithTwoMocha = new Mocha(espressoWithOneMocha); Console.WriteLine($"Espresso with Two mocha: {espressoWithTwoMocha.cost()}"); } }