Prototype Pattern

Introduction and Implementation of Prototype Pattern


Category: Design Patterns Tags: C#


Introduction

        Prototype Pattern is another creational design pattern where type of object which has to be created is determined by a prototype and can be cloned to produce new objects. It actually provides a facility to clone object so you no need to use new keyword to create new objects.

Implementation

        To implement this we have to create an abstract class with abstract method called Clone which can be used for cloning. Clone method returns same prototype:

abstract class ComputerPrototype
{
public abstract ComputerPrototype Clone();
}

Now we have to override this method in concrete class:

class Computer : ComputerPrototype
{
private string _name;
public Computer(string name)
{
_name = name;
}

public override ComputerPrototype Clone()
{
Console.WriteLine("Cloning {0}", _name);
return (ComputerPrototype)this.MemberwiseClone();
}
}

In above class we overridden clone method, when we clone instant we have _name which will help us to understand which object is getting cloned. Clone method uses MemberwiseClone which is inbuilt method provides shallow cloning of an object. Means it creates new object and copy the data to new instance. Now we will create manager class which will maintain all the instances:

class ComputerManger
{
Dictionary<string, ComputerPrototype> _computers = new Dictionary<string, ComputerPrototype>();

/// <summary>
/// Indexer
/// </summary>
public ComputerPrototype this[string key]
{
get { return _computers[key]; }
set { _computers[key] = value; }
}
}

Above class will maintain the objects and we can use these object for cloning. Now we will execute this code in Main method like:

ComputerManger manager = new ComputerManger();
manager["HP"] = new Computer("hp");
manager["Dell"] = new Computer("dell");

manager["Lenovo"] = manager["HP"].Clone();

Above we created two objects of computer named hp and dell and created one more named lenovo cloning hp. when it clones hp we can see message on console:

 

Cloning hp

 

So prototype is simple to implement and we can extend prototype class to n number of classes and can provide functionality of cloning.


Like 0 People
Last modified on 16 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 129
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x