原型模型
跟单例模型只创建一个对象相反,原型模型用于快速的创建相同的多个对象。
public class ProtoType { private static ProtoType protoType = new ProtoType(); public string sDBconnection = ""; private ProtoType() { Console.WriteLine("构造函数初始化!!"); } public static ProtoType CreateInstance(string sdb) { ProtoType _protoType = (ProtoType)protoType.MemberwiseClone(); _protoType.sDBconnection = sdb; return _protoType; } }
Main中调用:
class Program { static void Main(string[] args) { ProtoType protoType = ProtoType.CreateInstance("server=1;database=a"); ProtoType protoType1 = ProtoType.CreateInstance("server=2;database=b"); ProtoType protoType2 = ProtoType.CreateInstance("server=3;database=c"); ProtoType protoType3 = ProtoType.CreateInstance("server=4;database=d"); Console.WriteLine(protoType.sDBconnection); Console.WriteLine(protoType1.sDBconnection); Console.WriteLine(protoType2.sDBconnection); Console.WriteLine(protoType3.sDBconnection); Console.Read(); } }
输出结果: