Pattern: Prototype
It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
Purpose of .NET implementation
If you want to clone an object ( that has members and methods ), the easy way is to copy the members into a new instance.
But if you have a complex object, you may want to use the Prototype pattern.
You then provide MemberwiseClone is a shallow copy for the members of an object.
However, the Prototype pattern is not used very often in .NET, because the ICloneable interface is not very useful.
Example in .NET :
ICloneable
ICloneable example for Pattern Prototype
using System;
namespace Prototype;
class Parent : ICloneable
{
public int Age { get; set; }
public Child MyChild { get; set; }
public object Clone()
{
//TODO: serialize + unserialize
//with System.Text.Json.JsonSerializer
var p = ShallowClone();
//TODO: clone the child
var c = new Child();
c.Age = this.MyChild.Age;
p.MyChild = c;
return p;
}
public Parent ShallowClone()
{
return this.MemberwiseClone() as Parent;
}
}
See Source Code for Microsoft implementation of Prototype
SourceCode Object.MemberwiseCloneLearn More
C2Wikidofactory
DPH
Wikipedia
Homework
Imagine that you have a cow farm and you want to create a new cow.
Implement a prototype that will allow you to clone a cow.
The cow should have a name and a weight.