原型模式
原型模式(Prototype pattern )
为什么要使用原型而不使用new操作符?1.创建对象不需初始化过程;2.保存部分原来对象的信息;3.解决子类爆炸问题。
当一个类族的数量不确定时,但是类与类之间有固定的联系,那么使用原型模式是比较好的解决方案。就向上面说的那样,原型创建新对象并不是通过new一个对象然后初始化来达到创建的目的的。我们只通过对已有对象的复制来实现。就像一俩车的外壳模型一样。我们需要各式各样车的外壳,但是这些外壳都是有固定部分改造而成的,车头,车身和车尾,对于不同的车外壳我们只要改造这个现有的模型而已,而不用重新从一个铁皮开始加工,哪怕我们用的材质不同,所以我们可以先开发一辆车的外壳,然后让所有的外壳都从该外壳上改造,这样即减少来开模的数量,还能节省成本。这就是原型的意义减少初始化的步骤,减少子类。
public enum RecordType
{
Car,
Person
}
/// <summary>
/// Record is the Prototype
/// </summary>
public abstract class Record
{
public abstract Record Clone();
}
/// <summary>
/// PersonRecord is the Concrete Prototype
/// </summary>
public class PersonRecord : Record
{
string name;
int age;
public override Record Clone()
{
return (Record)this.MemberwiseClone(); // default shallow copy
}
}
/// <summary>
/// CarRecord is another Concrete Prototype
/// </summary>
public class CarRecord : Record
{
string carname;
Guid id;
public override Record Clone()
{
CarRecord clone = (CarRecord)this.MemberwiseClone(); // default shallow copy
clone.id = Guid.NewGuid(); // always generate new id
return clone;
}
}
/// <summary>
/// RecordFactory is the client
/// </summary>
public class RecordFactory
{
private static Dictionary<RecordType, Record> _prototypes =
new Dictionary<RecordType, Record>();
/// <summary>
/// Constructor
/// </summary>
public RecordFactory()
{
_prototypes.Add(RecordType.Car, new CarRecord());
_prototypes.Add(RecordType.Person, new PersonRecord());
}
/// <summary>
/// The Factory method
/// </summary>
public Record CreateRecord(RecordType type)
{
return _prototypes[type].Clone();
}
}
{
Car,
Person
}
/// <summary>
/// Record is the Prototype
/// </summary>
public abstract class Record
{
public abstract Record Clone();
}
/// <summary>
/// PersonRecord is the Concrete Prototype
/// </summary>
public class PersonRecord : Record
{
string name;
int age;
public override Record Clone()
{
return (Record)this.MemberwiseClone(); // default shallow copy
}
}
/// <summary>
/// CarRecord is another Concrete Prototype
/// </summary>
public class CarRecord : Record
{
string carname;
Guid id;
public override Record Clone()
{
CarRecord clone = (CarRecord)this.MemberwiseClone(); // default shallow copy
clone.id = Guid.NewGuid(); // always generate new id
return clone;
}
}
/// <summary>
/// RecordFactory is the client
/// </summary>
public class RecordFactory
{
private static Dictionary<RecordType, Record> _prototypes =
new Dictionary<RecordType, Record>();
/// <summary>
/// Constructor
/// </summary>
public RecordFactory()
{
_prototypes.Add(RecordType.Car, new CarRecord());
_prototypes.Add(RecordType.Person, new PersonRecord());
}
/// <summary>
/// The Factory method
/// </summary>
public Record CreateRecord(RecordType type)
{
return _prototypes[type].Clone();
}
}
将想法付诸于实践,借此来影响他人是一个人存在的真正价值