dart设计模式之装饰器模式
装饰器模式(Decorator Pattern)
模式分析
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。
模式难点
实现现有抽象对象并传入已实现的抽象对象,并加入自定义方法
模式解决问题
一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
优点
装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点
多层装饰比较复杂。
模式应用场景
- 扩展一个类的功能。
- 动态增加功能,动态撤销。
模式代码
//创建接口
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接口的抽象类
class ShapeDecorator implements Shape {
final Shape decoratedShape;
ShapeDecorator(this.decoratedShape);
@override
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");
}
}
//使用 RedShapeDecorator 来装饰 Shape 对象。
class RunDecorator implements Run {
@override
void main() {
Shape circle = new Circle();
// ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
// ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
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();
}
@override
String name = "装饰器模式";
}
最后
这里也为想要学习Flutter的朋友们准备了两份学习资料《Flutter Dart语言编程入门到精通》《Flutter实战》,从编程语言到项目实战,一条龙服务!!
《Flutter Dart 语言编程入门到精通》
- 第一章 Dart语言基础
- 第二章 Dart 异步编程
- 第三章 异步之 Stream 详解
- 第四章 Dart标准输入输出流
- 第五章 Dart 网络编程
- 第六章 Flutter 爬虫与服务端
- 第七章 Dart 的服务端开发
- 第八章 Dart 调用C语言混合编程
- 第九章 LuaDardo中Dart与Lua的相互调用
《Flutter实战:第二版》
- 第一章:起步
- 第二章:第一个Flutter应用
- 第三章:基础组件
- 第四章:布局类组件
- 第五章:容器类组件
- 第六章:可滚动组件
- 第七章:功能型组件
- 第八章:事件处理与通知
- 第九章:动画
- 第十章:自定义组件
- 第十一章:文件操作与网络请求
- 第十二章:Flutter扩展
- 第十三章:国际化
- 第十四章:Flutter核心原理
- 第十五章:一个完整的Flutter应用