Prototype Pattern
From Logic Wiki
Create new objects by copying an existing object (the prototype) instead of instantiating from scratch.
What problem it solves
When:
- object creation is expensive or complex
- you need many similar objects
- you want to avoid tight coupling to concrete classes
…you clone instead of new.
public class Document : ICloneable
{
public string Title { get; set; }
public List<string> Pages { get; set; }
public object Clone()
{
// deep copy
return new Document
{
Title = this.Title,
Pages = new List<string>(this.Pages)
};
}
}
Usage
Document original = new Document
{
Title = "Report",
Pages = new List<string> { "Intro", "Body" }
};
Document copy = (Document)original.Clone();
copy.Title = "Report Copy";