04 Dec 2023
The Prototype design pattern is a creational pattern that allows the creation of new objects by copying an existing object, known as the prototype. In C#, the Prototype pattern typically involves the following main components:
-
Prototype Interface/Abstract Class:
- Declares a method for cloning itself.
- All classes that implement this interface or derive from this abstract class must provide an implementation for the cloning method.
public interface IPrototype<T> { T Clone(); } -
Concrete Prototype:
- Implements the Prototype interface.
- Defines a method for cloning itself.
- Provides a concrete implementation of the cloning logic.
public class ConcretePrototype : IPrototype<ConcretePrototype> { public int Property1 { get; set; } public string Property2 { get; set; } public ConcretePrototype Clone() { // Perform a deep copy or a shallow copy based on the requirement return new ConcretePrototype { Property1 = this.Property1, Property2 = this.Property2 }; } } -
Client:
- Requests the creation of a new object by cloning an existing prototype.
- Uses the cloning method to create copies of the prototype.
class Client { static void Main() { ConcretePrototype prototype = new ConcretePrototype { Property1 = 1, Property2 = "Prototype" }; // Clone the prototype to create a new object ConcretePrototype clone = prototype.Clone(); // Use the cloned object Console.WriteLine(clone.Property1); // Output: 1 Console.WriteLine(clone.Property2); // Output: Prototype } }
In the example above, ConcretePrototype is a class that implements the IPrototype<ConcretePrototype> interface. It provides a Clone method that creates a new object and copies the values of its properties from the original object.
The Client uses the prototype pattern by creating an instance of the concrete prototype and then cloning it to obtain a new object with the same properties. This allows the client to create new objects without explicitly instantiating them using constructors. The pattern is particularly useful when the cost of creating a new object is more expensive than copying an existing one.