74 lines
2.0 KiB
Dart
74 lines
2.0 KiB
Dart
/**
|
||
享元模式(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;
|
||
}
|
||
}
|