/** 装饰器模式(Decorator Pattern) 意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。 主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。 何时使用:在不想增加很多子类的情况下扩展类。 如何解决:将具体功能职责划分,同时继承装饰者模式。 */ main(List args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); print("Circle with normal border"); circle.draw(); print("\nCircle of red border"); redCircle.draw(); print("\nRectangle of red border"); redRectangle.draw(); } ////////////////////////////////////////////////////////////////// /// /// 创建一个接口 /// abstract class Shape { void draw(); } /// /// 创建实现接口的实体类 /// class Rectangle implements Shape { @override void draw() { print("Shape: Rectangle"); } } class Circle implements Shape { @override void draw() { print("Shape: Circle"); } } /// /// 创建实现了 Shape 接口的抽象装饰类 /// abstract class ShapeDecorator implements Shape { Shape _decoratedShape; ShapeDecorator(this._decoratedShape); void draw() { _decoratedShape.draw(); } } /// /// 创建扩展了 ShapeDecorator 类的实体装饰类 /// class RedShapeDecorator extends ShapeDecorator { RedShapeDecorator(Shape decoratedShape) : super(decoratedShape); @override void draw() { _decoratedShape.draw(); setRedBorder(_decoratedShape); } void setRedBorder(Shape decoratedShape) { print("Border Color: Red"); } }