当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
18 Star 81 Fork 26

ryanpenn / dart_in_action
暂停

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
22_design_pattern_decorator.dart 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
ryanpenn 提交于 2019-03-27 10:55 . dart programming
/**
装饰器模式(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");
}
}
Dart
1
https://gitee.com/ryanpenn/dart_in_action.git
git@gitee.com:ryanpenn/dart_in_action.git
ryanpenn
dart_in_action
dart_in_action
master

搜索帮助