Posted on 2009-06-13 11:43
sufan 阅读(355)
评论(0) 编辑 收藏 引用 所属分类:
转载
sourcemaking 上关于抽象工厂方法的例子代码,个人感觉非常利于理解,看看这些代码,比读几遍书貌似有效果的多~~~
1 #include <iostream.h>
2
3 class Shape {
4 public:
5 Shape() {
6 id_ = total_++;
7 }
8 virtual void draw() = 0;
9 protected:
10 int id_;
11 static int total_;
12 };
13 int Shape::total_ = 0;
14
15 class Circle : public Shape {
16 public:
17 void draw() {
18 cout << "circle " << id_ << ": draw" << endl;
19 }
20 };
21 class Square : public Shape {
22 public:
23 void draw() {
24 cout << "square " << id_ << ": draw" << endl;
25 }
26 };
27 class Ellipse : public Shape {
28 public:
29 void draw() {
30 cout << "ellipse " << id_ << ": draw" << endl;
31 }
32 };
33 class Rectangle : public Shape {
34 public:
35 void draw() {
36 cout << "rectangle " << id_ << ": draw" << endl;
37 }
38 };
39
40 class Factory {
41 public:
42 virtual Shape* createCurvedInstance() = 0;
43 virtual Shape* createStraightInstance() = 0;
44 };
45
46 class SimpleShapeFactory : public Factory {
47 public:
48 Shape* createCurvedInstance() {
49 return new Circle;
50 }
51 Shape* createStraightInstance() {
52 return new Square;
53 }
54 };
55 class RobustShapeFactory : public Factory {
56 public:
57 Shape* createCurvedInstance() {
58 return new Ellipse;
59 }
60 Shape* createStraightInstance() {
61 return new Rectangle;
62 }
63 };
64
65 int main() {
66 #ifdef SIMPLE
67 Factory* factory = new SimpleShapeFactory;
68 #elif ROBUST
69 Factory* factory = new RobustShapeFactory;
70 #endif
71 Shape* shapes[3];
72
73 shapes[0] = factory->createCurvedInstance(); // shapes[0] = new Ellipse;
74 shapes[1] = factory->createStraightInstance(); // shapes[1] = new Rectangle;
75 shapes[2] = factory->createCurvedInstance(); // shapes[2] = new Ellipse;
76
77 for (int i=0; i < 3; i++) {
78 shapes[i]->draw();
79 }
80 }
输出为:
ellipse 0: draw
rectangle 1: draw
ellipse 2: draw