设计模式——简单工厂模式(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 }
相关文章推荐
- 极速理解设计模式系列:21.简单工厂模式(Simple Factory Pattern)
- 设计模式(Design Pattern) - 创建型模式(Creational Pattern) - 简单工厂模式(Simple Factory Pattern) - Java实现
- 设计模式——简单工厂模式(simple factory pattern)
- 设计模式(创建型)之简单工厂模式(Simple Factory Pattern)
- 设计模式-简单工厂模式(simple factory)
- 极速理解设计模式系列:21.简单工厂模式(Simple Factory Pattern)
- c++设计模式:简单工厂模式(Simple Factory Pattern)
- 解读设计模式----简单工厂模式(SimpleFactory Pattern),你要什么我就给你什么
- JAVA设计模式之 简单工厂模式【Simple Factory Pattern】
- 设计模式之简单工厂模式(Simple Factory)
- 角色产品设计模式之八:简单工厂模式(Simple Factory pattern)
- C++ 设计模式之——简单工厂模式(SimpleFactoryPattern)
- Java设计模式 - 简单工厂模式(Simple Factory)
- 设计模式笔记之工厂模式--简单工厂模式(Simple Factory Pattern)
- 设计模式-简单工厂模式(SimpleFactory)
- 解读设计模式----简单工厂模式(SimpleFactory Pattern),你要什么我就给你什么
- JAVA设计模式(01):创建型-工厂模式【简单工厂模式】(Simple Factory)
- 解读设计模式----简单工厂模式(SimpleFactory Pattern),你要什么我就给你什么 推荐
- 设计模式之简单工厂模式(Simple Factory)
- [设计模式]简单工厂模式(Simple Factory)