What is the Prototype Design Pattern ?

 Posted by Bharathi Cherukuri on 4/26/2012 | Category: .NET Framework Interview questions | Views: 1872 | Points: 40
Answer:

A prototype design pattern relies on creation of clones rather than objects.
Here, we avoid using the keyword 'new' to prevent overheads.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Rajni.Shekhar on: 4/27/2012 | Points: 10
can you please give some example of prototype design.
Posted by: Bharathi Cherukuri on: 4/27/2012 | Points: 10
Sure Rajini..

Example:

//Note: In this example ICloneable interface (defined in .Net Framework) acts as Prototype

class ConcretePrototype : ICloneable

{
public int X { get; set; }

public ConcretePrototype(int x)
{
this.X = x;
}

public void PrintX()
{
Console.WriteLine("Value :" + X);
}

public object Clone()
{
return this.MemberwiseClone();
}
}

/**
* Client code
*/
public class PrototypeTest
{
public static void Main()
{
var prototype = new ConcretePrototype(1000);

for (int i = 1; i < 10; i++)
{
ConcretePrototype tempotype = prototype.Clone() as ConcretePrototype;

// Usage of values in prototype to derive a new value.
tempotype.X *= i;
tempotype.PrintX();
}
Console.ReadKey();
}
}

/*
**Code output**

Value :1000
Value :2000
Value :3000
Value :4000
Value :5000
Value :6000
Value :7000
Value :8000
Value :9000
*/


Regards,
Bharathi

Login to post response