The Prototype pattern is used when you need to create new objects from an existing instance instead of instantiating them directly. It allows copying (cloning) objects, which is useful when creating a new object from scratch is complex or costly. This pattern is commonly used in situations where you need to create multiple instances of similar objects with slight variations, like creating documents or graphics in an editor while maintaining some common properties.
C# Code Example:
// Prototype Interface
public interface IPrototype<T>
{
T Clone();
}
// Concrete class implementing Prototype
public class Circle : IPrototype<Circle>
{
public int Radius { get; set; }
public Circle(int radius)
{
Radius = radius;
}
public Circle Clone()
{
// Clone the current object
return new Circle(this.Radius);
}
public void ShowDetails()
{
Console.WriteLine($"Circle with radius: {Radius}");
}
}
class Program
{
static void Main(string[] args)
{
// Create an original circle
Circle circle1 = new Circle(10);
circle1.ShowDetails(); // Output: Circle with radius: 10
// Clone the circle
Circle circle2 = circle1.Clone();
circle2.ShowDetails(); // Output: Circle with radius: 10
// Modify the clone
circle2.Radius = 20;
circle2.ShowDetails(); // Output: Circle with radius: 20
circle1.ShowDetails(); // Output: Circle with radius: 10
}
}
Code Explanation:
In this example, the Circle class implements the IPrototype interface, which defines the Clone method. The Clone method creates a new instance of Circle with the same properties as the original object. The main code demonstrates the creation of a circle, its cloning, and how changes to the cloned object do not affect the original.
Conclusion:
The Prototype pattern is ideal for efficiently creating copies of objects, especially when creating new objects from scratch is complex or resource-intensive. It is useful when you need to create multiple similar objects, allowing you to copy an existing instance and modify it as needed.
Source code: GitHub
Top comments (0)