Prototype

Originally published 2016-02-20 · Boris Ivanov

1. Usage

Pool of prototypical instances copying them-self to create new copy of objects. Reason can be expensive usage of new() command. Also such approach hide complexity.

2. UML class diagram

prototype2

3. Pros

4. Cons

Each subclass of Prototype must implement Clone operation, which may be difficult.(internals include objects which dont support copying or have circular references).

5. Source code


/**********************
 2016 (C) Boris Ivanov.
 Prototype Design Pattern 
 C++ implementation
 ********************/

#include <iostream>

using namespace std;


// Abstract class.
class ProtoSheep{

protected:
    string _name;
    int _age;

public:
    virtual ProtoSheep* clone () = 0;
    string getName(){
        return _name;
    }

    int getAge(){
        return _age;
    }
};


// Concrete class.
class BlackSheep : public ProtoSheep{
public:
    BlackSheep(int age, string name){
        _name = name;
        _age = age;
    }

    ProtoSheep* clone(){
        // Default Constructor used.
        return new BlackSheep(*this);
    }
};


// Factory to manage prototypes and clone them.
class SheepFactory
{
    static ProtoSheep* sheep;

public:
    static void Init(){
        sheep = new BlackSheep(3, "Blacky");
    }

    static ProtoSheep* CloneBlackSheep(){
        return sheep->clone();
    }

};

// Linker need to have it outside class declaration.
ProtoSheep * SheepFactory::sheep = 0;

int main()
{
    ProtoSheep * Dolly;
    ProtoSheep * Dolly2;

    SheepFactory::Init();

    Dolly = SheepFactory::CloneBlackSheep();
    Dolly2 = SheepFactory::CloneBlackSheep();
    cout << Dolly->getName() << ":" << Dolly->getAge() << "\n";
    cout << Dolly2->getName() << ":" << Dolly2->getAge() << "\n";
    return 0;
}