Factory Method Design Pattern Description
Source Code of Factory Design Pattern Example in C++
/* * File:factory.cpp * This file is described the Factory Design Pattern with help of example * Author: Aplha * Date: 28 Dec 2020 */ //Header File #include<iostream> //Pizza class Pizza { public: virtual void BakePizza()=0; }; class DominoPanerrPiza : public Pizza { public: void BakePizza() { std::cout<<"DominoPanerrPiza is ready"<<std::endl; } }; class DominoCheesePiza : public Pizza { public: void BakePizza() { std::cout<<"DominoCheesePiza is ready"<<std::endl; } }; //class PizzaFactory class PizzaFactory { protected: Pizza* _mPizza; public: void OrderPizza(std::string type) { _mPizza = CreatePizza(type); _mPizza->BakePizza(); } private: virtual Pizza* CreatePizza(std::string type)=0; }; //DominoPizzaFactory class DominoPizzaFactory:public PizzaFactory { private: Pizza* CreatePizza(std::string type) { Pizza* pz = nullptr; if(type == "Paneer") pz = new DominoPanerrPiza; return pz; } }; //Client int main() { std::cout<<"In Main"<<std::endl; //Select Factory PizzaFactory* ptr = new DominoPizzaFactory; //Order the Pizza with type std::cout<<"Ordering Paneer Pizza from Domino"<<std::endl; ptr->OrderPizza("Paneer"); std::cout<<"!!!!!!!!!!Got the Pizza!!!!!!!!!"<<std::endl; return 0; }
Compilation Command:
g++ -std=c++11 factory.cpp
Output:
In Main
Ordering Paneer Pizza from Domino
DominoPanerrPiza is ready
!!!!!!!!!!Got the Pizza!!!!!!!!!
Factory Method Design Pattern Description