1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 //product
6 class Shape
7 {
8 public:
9 virtual void draw() = 0;
10 virtual ~Shape() {}
11 };
12
13 class Circle : public Shape
14 {
15 public:
16 void draw() { cout << "Circle::draw" << endl; }
17 ~Circle() { cout << "Circle::~Circle" << endl; }
18 private:
19 Circle() {}
20 friend class SimpleFactory;
21 };
22
23 class Square : public Shape
24 {
25 public:
26 void draw() { cout << "Square::draw" << endl; }
27 ~Square() { cout << "Square::~Square" << endl; }
28 private:
29 Square() {}
30 friend class SimpleFactory;
31 };
32
33 //factory
34 class SimpleFactory
35 {
36 public:
37 static Shape* create(const string& type)
38 {
39 if(type == "Circle") return new Circle;
40 if(type == "Square") return new Square;
41 //...
42 return NULL;
43 }
44 };
45
46 int main()
47 {
48 Shape* pShape1 = SimpleFactory::create("Circle");
49 Shape* pShape2 = SimpleFactory::create("Square");
50
51 pShape1->draw();
52 pShape2->draw();
53
54 delete pShape1;
55 delete pShape2;
56
57 return 0;
58 }