首页 > 代码库 > 工厂模式

工厂模式

简单工厂模式(simple factory)是类的创建模式,又叫静态工厂方法(static factory method)模式。

简单工厂模式就是由一个工厂类根据传入的参数决定创建哪一种的产品类。

 

有4个角色

 

工厂类角色:是具体产品类角色直接调用者。 

抽象产品角色:接口或抽象类,负责具体产品角色的定义,及与客户端的交互。 

具体产品角色:被工厂类创建的对象,也是客户端实际操作对象。 

客户端:调用工厂类产生实例,并调用实例的方法进行相应工作。


c++实现

#include <iostream>

#include <list>


using namespace std;
class Pizza
{
public:
    string name;
    string dough;
    string sauce;
    list<string> pizzalist;
    void prepare()
    {
        cout<<"Preparing"+name<<endl;
        cout<<"Tossing dough..."<<endl;
        cout<<"Adding sauce..."<<endl;
        cout<<"Adding pizzalist: "<<endl;
        for(list<string>::iterator it=pizzalist.begin();it!=pizzalist.end();it++)
        {
            cout<<"  "<<*it<<endl;
        }
    }
    virtual void bake()
    {
        cout<<"Bake for 25 minutes at 350"<<endl;
    }
    virtual void cut()
    {
        cout<<"Cutting the pizza into diagonal slices"<<endl;
    }
    virtual void box()
    {
        cout<<"Place pizza in official PizzaStore box"<<endl;
    }
    string getName()
    {
        return name;
    }
};
class NYstyleCheesePizza:public Pizza
{
  public:
   NYstyleCheesePizza()
  {
      name="NY Style Sauce and Cheese Pizza";
      dough="Thin Crust Dough";
      sauce="Marinara Sauce";
      pizzalist.push_back("Grated Reggiano Cheese");
  }
};
class ChicagoStyleCheesePizza:public Pizza
{
  public:
  ChicagoStyleCheesePizza()
  {
      name="Chicago Style Deep Dish Cheese Pizza";
      dough="Extra Thick Crust Dough";
      sauce="Plum Tomato Sauce";
      pizzalist.push_back("Shredded Mozzarella Cheese");
  }
  void cut()
  {
      cout<<"Cutting the pizza into square slices";
  }


};
class PizzaStore
{
    public :
    Pizza orderPizza(string type)
    {
        Pizza pizza;
        pizza=creatPizza(type);
        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();
        return pizza;
    }
    protected:
        virtual Pizza creatPizza(string type)=0;
};
class NYStylePizzaStore:public PizzaStore
{
    Pizza creatPizza(string item)
    {
        if(item=="cheese")
        {
            NYstyleCheesePizza ny;
            return ny;
        }
    }


};
class ChicagoStyleStore:public PizzaStore
{
  Pizza creatPizza(string item)
  {
      if(item=="cheese")
      {
          ChicagoStyleCheesePizza chicago;
          return chicago;
      }


  }
};
int main()
{
    PizzaStore *nyStore=new NYStylePizzaStore();
    PizzaStore *chicagoStore=new ChicagoStyleStore();
    Pizza pizza =nyStore->orderPizza("cheese");
    cout<<"Ethan ordered a "+pizza.getName()<<endl;
    pizza =chicagoStore->orderPizza("cheese");
    cout<<"Joel ordered a "+pizza.getName()<<endl;
    return 0;
}