您的位置:首页 > 其它

设计模式——简单工厂模式(Simple Factory)

2012-12-30 17:23 369 查看
即将对象创建封装到工厂类中,用户传递参数给工厂对象,获取相应对象。

通过多态,将用户与具体对象隔离开



代码示例

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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐