dart_in_action/13_design_pattern_factory.dart

81 lines
1.9 KiB
Dart
Raw Normal View History

2019-03-27 10:55:27 +08:00
/**
(Factory Pattern)
使
使
*/
main(List<String> args) {
var shapeFactory = ShapeFactory();
//获取 Circle 的对象,并调用它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
//调用 Circle 的 draw 方法
shape1.draw();
//获取 Rectangle 的对象,并调用它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//调用 Rectangle 的 draw 方法
shape2.draw();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//调用 Square 的 draw 方法
shape3.draw();
}
//////////////////////////////////////////////////////////////////
///
/// 创建一个接口
///
abstract class Shape {
void draw();
}
///
/// 创建实现接口的实体类
///
class Rectangle implements Shape {
@override
void draw() {
print("Inside Rectangle::draw() method.");
}
}
class Square implements Shape {
@override
void draw() {
print("Inside Square::draw() method.");
}
}
class Circle implements Shape {
@override
void draw() {
print("Inside Circle::draw() method.");
}
}
///
/// 创建一个工厂
///
class ShapeFactory {
//使用 getShape 方法获取形状类型的对象
Shape getShape(String shapeType) {
switch (shapeType?.toUpperCase()) {
case "CIRCLE":
return Circle();
break;
case "RECTANGLE":
return Rectangle();
break;
case "SQUARE":
return Square();
break;
default:
return null;
}
}
}