dart_in_action/22_design_pattern_decorator...

80 lines
1.8 KiB
Dart
Raw Normal View History

2019-03-27 10:55:27 +08:00
/**
Decorator Pattern
使
使
*/
main(List<String> 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");
}
}