skip to content
Mohammad Rebati

Understanding the Prototype Design Pattern

/ 2 min read

Introduction to the Prototype Design Pattern

The Prototype Design Pattern is a creational design pattern that involves creating objects based on a template of an existing object through cloning. This pattern is used when the creation of an object directly is costly or complicated. Instead, an initial prototype is created and new objects are cloned from this prototype, with the possibility to alter them afterwards.

Key Concepts

  • Prototype: A fully initialized instance to be copied or cloned.
  • Concrete Prototype: A subclass that implements the cloning method to create new objects from itself.
  • Client: The part of the application that manages cloning of objects using the prototype.

Benefits

  • Efficiency: Avoids the cost of new creation and speeds up the instantiation process.
  • Flexibility: Allows adding or removing objects at runtime.
  • Customization: Newly created instances can be modified after cloning to meet specific needs.

Example in Code

Here’s how you might implement the Prototype Pattern in C# for cloning graphical objects in a design application:

// Prototype
public abstract class Graphic
{
public abstract Graphic Clone();
}
// Concrete Prototype
public class Circle : Graphic
{
public int Radius { get; set; }
public Circle() { }
public Circle(Circle circle)
{
Radius = circle.Radius;
}
public override Graphic Clone()
{
return new Circle(this);
}
public void Draw()
{
Console.WriteLine($"Drawing circle with radius: {Radius}");
}
}
// Client
public class GraphicTool
{
private Graphic _prototype;
public GraphicTool(Graphic prototype)
{
_prototype = prototype;
}
public Graphic CreateGraphic()
{
return _prototype.Clone();
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
Graphic circlePrototype = new Circle { Radius = 5 };
GraphicTool tool = new GraphicTool(circlePrototype);
Graphic clonedCircle = tool.CreateGraphic();
((Circle)clonedCircle).Draw();
// Modify prototype and clone again
((Circle)circlePrototype).Radius = 10;
clonedCircle = tool.CreateGraphic();
((Circle)clonedCircle).Draw();
}
}