The Prototype design pattern is a creational pattern that allows you to create copies of objects without exposing their underlying structure. This is particularly useful when creating new objects is more efficient by copying an existing object rather than creating them from scratch. Let’s create an example of the Prototype pattern in C# with a use case of cloning shapes.
Create the Prototype Interface
Define an interface for the prototypes, declaring a method for cloning objects.
public interface IShape
{
IShape Clone();
void Draw();
}
Create Concrete Prototype Classes
Implement the IShape
interface in concrete classes representing different shapes.
public class Circle : IShape
{
private int radius;
public Circle(int radius)
{
this.radius = radius;
}
public IShape Clone()
{
return new Circle(this.radius);
}
public void Draw()
{
Console.WriteLine("Draw a Circle with radius " + radius);
}
}
public class Square : IShape
{
private int side;
public Square(int side)
{
this.side = side;
}
public IShape Clone()
{
return new Square(this.side);
}
public void Draw()
{
Console.WriteLine("Draw a Square with side " + side);
}
}
Create a PrototypeManager
This class maintains a dictionary of prototype objects.
public class PrototypeManager
{
private Dictionary<string, IShape> shapePrototypes = new Dictionary<string, IShape>();
public void AddShapePrototype(string key, IShape prototype)
{
shapePrototypes[key] = prototype;
}
public IShape GetShapeClone(string key)
{
if (shapePrototypes.TryGetValue(key, out IShape prototype))
{
return prototype.Clone();
}
return null;
}
}
Use Case – Cloning Shapes
In this use case, we’ll use the Prototype pattern to create copies of shapes stored in the PrototypeManager
.
class Program
{
static void Main(string[] args)
{
var manager = new PrototypeManager();
// Create and add shape prototypes to the manager
manager.AddShapePrototype("circle", new Circle(5));
manager.AddShapePrototype("square", new Square(4));
// Clone and draw shapes
IShape clonedCircle = manager.GetShapeClone("circle");
IShape clonedSquare = manager.GetShapeClone("square");
clonedCircle.Draw();
clonedSquare.Draw();
}
}
In this example, we create a PrototypeManager
that maintains shape prototypes (circles and squares). When you need a clone of a shape, you call GetShapeClone
from the manager, which returns a cloned shape based on the prototype. This allows you to efficiently create new objects by copying existing ones, without exposing the details of how the shapes are constructed.