C++ Prototype Design Pattern:
Standard Definition:
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
In layman language:
It is same like that first writer gives the prototype of book then clone this and create many copy of it.
Problem:
We need a lots of similar objects but basic object is same.
Solution:
We can take/preserve a basic object then on demand we can clone from it and add or remove some functionality to it if required and this solution called as “Prototype design pattern“.
When we will use prototype design pattern:
- When we need to create many similar objects at run time and we know the basic prototype.
Advantage:
- We don’t need separate hierarchy like factory design pattern to create a product.
- At run time, we can add/remove the prototype object.
- At run time, we can clone any number of object on demand if required.
Source code:
/* Program:Prototype Design Pattern Author: Alpha Master Date: 21 Nov 2021 */ //Header File #include<iostream> #include<vector> //Prototype Base clone class ProtoType { public: virtual ProtoType* clone() = 0; virtual void tellYourName() = 0; }; class Hero :public ProtoType { //int staticValue; public: ProtoType* clone() { return new Hero(*this);} void tellYourName() {std::cout<<"Hero"<<std::endl;} }; class Villain :public ProtoType { public: ProtoType* clone() { return new Villain(*this);} void tellYourName() {std::cout<<"Villain"<<std::endl;} }; //client int main() { std::cout<<"ProtoType Pattern"<<std::endl; //sample of object or prototype that will be used to create new objects //below sample of objects can be keep in separate class. ProtoType* pArray[2] = {new Hero, new Villain}; std::vector<ProtoType*>v1; int choice = 0; while(1) { std::cout<<"Enter the choice 1 for hero, 2 for Villain and for exit 3"<<std::endl; std::cin>>choice; if(choice == 1) { v1.push_back(pArray[0]->clone()); } else if(choice == 2) { v1.push_back(pArray[1]->clone()); } else if(choice == 3) break; else std::cout<<"Wrong Choice"<<std::endl; } //we have created the heros and villains std::vector<ProtoType*> :: iterator itr = v1.begin(); for(;itr != v1.end(); itr++) { (*itr)->tellYourName(); } return 0; }
Output:
ProtoType Pattern Enter the choice 1 for hero, 2 for Villain and for exit 3 1 Enter the choice 1 for hero, 2 for Villain and for exit 3 1 Enter the choice 1 for hero, 2 for Villain and for exit 3 2 Enter the choice 1 for hero, 2 for Villain and for exit 3 2 Enter the choice 1 for hero, 2 for Villain and for exit 3 3 Hero Hero Villain Villain