Prototype

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

  • Adding and removing products at run-time.
  • Specifying new objects by varying values.
  • Specifying new objects by varying structure.
  • Reduced sub-classing.
  • Configuring an application with classes dynamically.

4. Cons

Each subclass of Prototype must implement Clone operation, which may be difficult.(internals include objects which don’t 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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *