Prototype Pattern
Summary: When the object construction reiterate existing designs. Its a partially or fully initialized object that you copy (clone) and make use of.
Sample Code
Custom Prototype Interface
public interface IPrototype<T>
{
T DeepCopy();
}
public class DigitalCamera : IPrototype<DigitalCamera>
{
public string Brand { get; set; }
public string Model { get; set; }
public DateTime Year { get; set; }
public override string ToString() => $"Brand: {Brand}, Model: {Model}, Year: {Year}";
public DigitalCamera DeepCopy()
{
return new DigitalCamera
{
Brand = this.Brand,
Model = this.Model,
Year = this.Year
};
}
}
var camera = new DigitalCamera();
camera.Brand = "Canon";
camera.Model = "70D";
camera.Year = new System.DateTime(2013,1,1);
var camera2 = camera.DeepCopy();
camera2.Model = "80D";
camera2.Year = new System.DateTime(2016,1,1);
WriteLine(camera);
WriteLine(camera2);
Brand: Canon, Model: 70D, Year: 01/01/2013 00:00:00
Brand: Canon, Model: 80D, Year: 01/01/2016 00:00:00
Serialized Copy Through Extension Interface
[Serializable]
public class DigitalCamera
{
public string Brand { get; set; }
public string Model { get; set; }
public DateTime Year { get; set; }
public override string ToString() => $"Brand: {Brand}, Model: {Model}, Year: {Year}";
}
public static class ExtensionMethods
{
public static T DeepCopy<T>(this T self)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, self);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
}
Usage
var camera = new DigitalCamera();
camera.Brand = "Canon";
camera.Model = "70D";
camera.Year = new System.DateTime(2013,1,1);
var camera2 = camera.DeepCopy();
camera2.Model = "80D";
camera2.Year = new System.DateTime(2016,1,1);
WriteLine(camera);
WriteLine(camera2);
Output
Brand: Canon, Model: 70D, Year: 01/01/2013 00:00:00
Brand: Canon, Model: 80D, Year: 01/01/2016 00:00:00
Comments
Post a Comment