dart_in_action/24_design_pattern_flyweight...

74 lines
2.0 KiB
Dart
Raw Permalink Normal View History

2019-03-27 10:55:27 +08:00
/**
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;
}
}