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

时间:2023-03-08 17:55:35

Pizza.h

 #ifndef _PIZZA_H
#define _PIZZA_H
#include <iostream>
#include <string> class Pizza
{
public:
Pizza(const std::string &type) : m_type(type) {}
virtual ~Pizza() {}
virtual void prepare() { std::cout << "prepare " << m_type << std::endl; }
virtual void bake() { std::cout << "bake " << m_type << std::endl; }
virtual void cut() { std::cout << "cut " << m_type << std::endl; }
virtual void box() { std::cout << "box " << m_type << std::endl; }
private:
std::string m_type;
};
#endif

CheesePizza.h

 #ifndef _CHEESE_PIZZA_H
#define _CHEESE_PIZZA_H
#include <iostream>
#include "Pizza.h" class CheesePizza : public Pizza
{
public:
CheesePizza() : Pizza("cheese") {}
~CheesePizza() {}
};
#endif

GreekPizza.h

 #ifndef _GREEK_PIZZA_H
#define _GREEK_PIZZA_H
#include <iostream>
#include "Pizza.h" class GreekPizza : public Pizza
{
public:
GreekPizza() : Pizza("greek") {}
~GreekPizza() {}
}; #endif

SimplePizzaFactory.h

 #ifndef _SIMPLE_PIZZA_FACTORY
#define _SIMPLE_PIZZA_FACTORY #include "CheesePizza.h"
#include "GreekPizza.h" class SimplePizzaFactory
{
public:
Pizza *CreatePizza(const std::string & type)
{
if ( "cheese" == type )
{
return new CheesePizza();
}
if ( "greek" == type )
{
return new GreekPizza();
}
return NULL;
}
};
#endif

PizzaStore.h

 #ifndef _PIZZA_STORE_H
#define _PIZZA_STORE_H
#include "SimplePizzaFactory.h" class PizzaStore
{
private:
SimplePizzaFactory pizza_factory;
public:
Pizza* OrderPizza(const std::string &type)
{
Pizza *p_pizza = pizza_factory.CreatePizza(type);
if (p_pizza)
{
p_pizza->prepare();
p_pizza->bake();
p_pizza->cut();
p_pizza->box();
}
return p_pizza;
}
};
#endif

main.cpp

 #include "PizzaStore.h"
int main()
{
PizzaStore pizza_store;
Pizza *p_pizza = pizza_store.OrderPizza("greek");
if ( p_pizza )
{
delete p_pizza;
}
return ;
}