Prototype Design Pattern in C++.
In Prototype Design pattern , we partially construct an object and store it somewhere.Then we clone the prototype and then customize the instance.
Motivation behind Prototype design pattern:
? Complicated objects (e.g., cars) aren’t designed from scratch - They reiterate existing designs
? An existing (partially constructed design) is a Prototype
? We make a copy (clone) the prototype and customize it
- Requires ‘deep copy’ support
- ? We make the cloning convenient (e.g., via a Factory)
Here is a very simple code to explain the idea:
#include<iostream> #include<memory> struct Address { std::string street; std::string city; int suite; friend std::ostream& operator<<(std::ostream& os , const Address& obj) { return os <<"street: "<<obj.street <<"city : "<<obj.city <<"suite: "<<obj.suite<<std::endl; } }; struct Contact { std::string name; std::unique_ptr<Address> work_address; Contact(const std::string& name, const std::unique_ptr<Address>& work_address):name{name}, work_address{std::make_unique<Address>(*work_address)} { } ~Contact() { } Contact(const Contact& other):name{other.name}, work_address{std::make_unique<Address>(*other.work_address)}{} friend std::ostream& operator<<(std::ostream& os, const Contact& obj) { return os <<"name: " << obj.name <<"work address: "<<*obj.work_address; } }; struct EmployeeFactory { static Contact main,aux; static std::unique_ptr<Contact> NewMainOfficeEmployee(const std::string& name,int suite) { return NewEmployeee(name, suite, main); } static std::unique_ptr<Contact> NewAuxOfficeEmployee(const std::string& name,int suite) { return NewEmployeee(name, suite, aux); } private: static std::unique_ptr<Contact> NewEmployeee(const std::string& name , int suite, Contact& office) { auto employee = std::make_unique<Contact>(office); employee->name = name; employee->work_address->suite = suite; return employee; } }; Contact EmployeeFactory::main{ "", std::unique_ptr<Address>(new Address{"123 Street", "Delhi", 0})}; Contact EmployeeFactory::aux{ "", std::unique_ptr<Address>(new Address{"123B Delhi", "Delhi", 0})}; int main() { auto sumit = EmployeeFactory::NewMainOfficeEmployee("sumit",23); std::cout<<"Debug: "<<*sumit<<std::endl; return 0; }