Search code examples
c++oopdesign-patternsfactory-pattern

Where to plug in the factory method in the abstract factory pattern?


// Abstract factory class

class pizzaStore
{
     public:
      vector <string> toppingsType;

      virtual void bakePizza        (){}
      virtual void preparePizza     ()
      {
           for (int i = 0; i < toppingsType.size (); i++)
           {
            addTopping (toppingsType[i]);
           }
      }

      virtual void cutPizza         (){}
      virtual void boxPizza     (){}
};

class xPizzaStore : public pizzaStore
{
     xPizzaStore () 
     {
      toppingsType = "1";
      sauceType      = "2";
      cheesetype     = "3";
     }

     void orderPizza ()
     {
      bakePizza ();
      preparePizza ();
      // xPizzaStore doesn't cut the pizza.
      boxPizza ();
     }
};

// Factory method for creating stores

pizzaStore * whichStore (string storeName)
{
      pizzaStore obj = NULL;

      if (storeName == "x")
      {
           obj = new xPizzaStore ();
      }
      else if (storeName == "y")
      {
           obj = new yPizzaStore ();
      }
      else if (storeName == "z")
      {
           obj = new zPizzaStore ();
      }

      return obj;
}

// Factory method for creating pizzas

pizzaStore * whichPizza (string pizzaName)
{
      pizzaName obj = NULL;

      if (pizzaBaseType == "x")
      {
           obj = new xPizzaName ();
      }
      else if (pizzaBaseType == "y")
      {
           obj = new yPizzaName ();
      }
      else if (pizzaBaseType == "z")
      {
           obj = new zPizzaName ();
      }

      return obj;
}

There can be different types of stores as well as pizzas.
In which class should these two factory methods be included and why? Does it make sense to include them in the pizzaStore class itself?


Solution

  • Does it make sense to include them in the pizzaStore class itself?

    Yes, it should be perfectly fine to put those method in class pizzaStore as static methods. Generally I consider, putting such factory method in a class based on its return type, and pizzaStore is a good candidate for it.