// Decorateor Pattern // 向一个现有的对象添加新的功能,同时又不改变其结构(方法签名不变)。 // 可动态的给一个对象添加一些额外的职责。比继承创建子类更灵活。 // // Step1: 创建一个接口 public interface Shape { void draw(); } // step2: 创建实现接口的实体类 Rectangle.cs Circle.cs public class Rectangle : Shape { public void draw() { console.writeline("Shape : Rectangle") } } public class Circle : Shape { public void draw() { console,writeline("Shape : Circle") } } // step3: 创建实现了 Shape 接口的抽象装饰类。ShapeDecorator.cs // 为何此处用抽象装饰类??
// 这一步在此处有些多余。可省略,直接用step4
public abstract class ShapeDecorator : Shape { protected Shape decoratedShape // 传入实体类,来被装饰; public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } public void draw() { decoratedShape.draw() } } // step4: 创建扩展了 ShapeDecorator 类的实体装饰类 RedShapeDecorator.cs // 在装饰类中,被装饰对象作为构造函数的 参数 传入 public class RedShapeDecorator : ShapeDecorator { private Shape decoratedShape; public RedShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } public void draw() { decoratedShape.draw(); // 先调用对象的原方法 setRedBorder(decoratedShape); // 给对象添加 装饰方法 } private void setRedBorder(Shape decoratedShape) { console.writeline("Border Color : Red"); } } public class DeocratorPatternDemo { public static void Main(string[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); circle.draw(); redCircle.draw(); redRectangel.draw(); } }