首页 > 编程语言 > 详细

Headfirst设计模式的C++实现——简单工厂模式(Simple Factory)

时间:2015-11-22 15:45:03      阅读:265      评论:0      收藏:0      [点我收藏+]

Pizza.h

 1 #ifndef _PIZZA_H
 2 #define _PIZZA_H
 3 #include <iostream>
 4 #include <string>
 5 
 6 class Pizza
 7 {
 8 public:
 9     Pizza(const std::string &type) : m_type(type) {}
10     virtual ~Pizza() {}
11     virtual void prepare() { std::cout << "prepare " << m_type << std::endl; }
12     virtual void bake() { std::cout << "bake " << m_type << std::endl; }
13     virtual void cut() { std::cout << "cut " << m_type << std::endl; }
14     virtual void box() { std::cout << "box " << m_type << std::endl; }
15 private:
16     std::string m_type;
17 };
18 #endif

CheesePizza.h

 1 #ifndef _CHEESE_PIZZA_H
 2 #define _CHEESE_PIZZA_H
 3 #include <iostream>
 4 #include "Pizza.h"
 5 
 6 class CheesePizza : public Pizza
 7 {
 8 public:
 9     CheesePizza() : Pizza("cheese") {}
10     ~CheesePizza() {}
11 };
12 #endif

GreekPizza.h

 1 #ifndef _GREEK_PIZZA_H
 2 #define _GREEK_PIZZA_H
 3 #include <iostream>
 4 #include "Pizza.h"
 5 
 6 class GreekPizza : public Pizza
 7 {
 8 public:
 9     GreekPizza() : Pizza("greek") {}
10     ~GreekPizza() {}
11 };
12 
13 #endif

SimplePizzaFactory.h

 1 #ifndef _SIMPLE_PIZZA_FACTORY
 2 #define _SIMPLE_PIZZA_FACTORY
 3 
 4 #include "CheesePizza.h"
 5 #include "GreekPizza.h"
 6 
 7 class SimplePizzaFactory
 8 {
 9 public:
10     Pizza *CreatePizza(const std::string & type)
11     {        
12         if ( "cheese" == type )
13         {
14             return new CheesePizza();
15         }
16         if ( "greek" == type )
17         {
18             return new GreekPizza();
19         }
20         return NULL;
21     }
22 };
23 #endif

PizzaStore.h

 1 #ifndef _PIZZA_STORE_H
 2 #define _PIZZA_STORE_H
 3 #include "SimplePizzaFactory.h"
 4 
 5 class PizzaStore
 6 {
 7 private:
 8     SimplePizzaFactory pizza_factory;
 9 public:
10     Pizza* OrderPizza(const std::string &type)
11     {
12         Pizza *p_pizza = pizza_factory.CreatePizza(type);
13         if (p_pizza)
14         {
15             p_pizza->prepare();
16             p_pizza->bake();
17             p_pizza->cut();
18             p_pizza->box();
19         }
20         return p_pizza;
21     }
22 };
23 #endif

main.cpp

 1 #include "PizzaStore.h"
 2 int main()
 3 {
 4     PizzaStore pizza_store;
 5     Pizza *p_pizza = pizza_store.OrderPizza("greek");
 6     if ( p_pizza )
 7     {
 8         delete p_pizza;
 9     }
10     return 0;
11 }

 

Headfirst设计模式的C++实现——简单工厂模式(Simple Factory)

原文:http://www.cnblogs.com/ren-yu/p/4985872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!