原型模式
Posted wskxy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原型模式相关的知识,希望对你有一定的参考价值。
1.回顾单例模式(Singleton Pattern)
设置一个静态的构造函数,让Student仅能被new一个,给所有调用返回一个相同的实例
StudentPrototype类代码如下:
using System; using System.Threading; namespace Prototype { class StudentPrototype { public String Name="kxy"; private StudentPrototype() { Thread.Sleep(2000); Console.WriteLine("执行StudentPrototype构造函数"); } private static StudentPrototype _studentPrototype=null; static StudentPrototype() { _studentPrototype = new StudentPrototype(); } public static StudentPrototype GetStudent() { return _studentPrototype; } } }
Program代码如下:
using System; namespace Prototype { class Program { static void Main(string[] args) { StudentPrototype studentPrototype1 = StudentPrototype.GetStudent(); studentPrototype1.Name = "flt"; StudentPrototype studentPrototype2 = StudentPrototype.GetStudent(); studentPrototype2.Name = "wzz"; StudentPrototype studentPrototype3 = StudentPrototype.GetStudent(); StudentPrototype studentPrototype4 = StudentPrototype.GetStudent(); Console.Read(); } } }
因为studentPrototype1和studentPrototype2是调用了同个实例,所以
当执行studentPrototype2.Name = "wzz"时,studentPrototype1的Name属性也会变成wzz
同理,studentPrototype3、studentPrototype4也是使用这个实例
2.原型模式(Prototype Pattern)
以上是关于原型模式的主要内容,如果未能解决你的问题,请参考以下文章