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

ryanpenn / dart_in_action
暂停

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
24_design_pattern_flyweight.dart 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
ryanpenn 提交于 2019-03-27 10:55 . dart programming
/**
享元模式(Flyweight Pattern)
意图:运用共享技术有效地支持大量细粒度的对象。
主要解决:在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
何时使用:
1、系统中有大量对象。
2、这些对象消耗大量内存。
3、这些对象的状态大部分可以外部化。
4、这些对象可以按照内蕴状态分为很多组,当把外蕴对象从对象中剔除出来时,每一组对象都可以用一个对象来代替。
5、系统不依赖于这些对象身份,这些对象是不可分辨的。
如何解决:用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。
*/
import 'dart:math';
main(List<String> args) {
final List<String> colors = ["Red", "Green", "Blue", "White", "Black"];
for (int i = 0; i < 20; ++i) {
Circle circle =
ShapeFactory.getCircle(colors[Random().nextInt(colors.length)]);
circle.x = Random().nextInt(100);
circle.y = Random().nextInt(100);
circle.radius = 100;
circle.draw();
}
}
//////////////////////////////////////////////////////////////////
///
/// 创建一个接口
///
abstract class Shape {
void draw();
}
///
/// 创建实现接口的实体类
///
class Circle implements Shape {
String color;
int x;
int y;
int radius;
Circle(String color) {
this.color = color;
}
@override
void draw() {
print("Circle: Draw() [Color : $color, x : $x, y :$y, radius :$radius");
}
}
///
/// 创建一个工厂,生成基于给定信息的实体类的对象
///
class ShapeFactory {
static final Map<String, Shape> circleMap = Map();
static Shape getCircle(String color) {
Circle circle = circleMap[color] as Circle;
if (circle == null) {
circle = new Circle(color);
circleMap[color] = circle;
print("Creating circle of color : $color");
}
return circle;
}
}
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

搜索帮助