首页 > 其他 > 详细

原型模式

时间:2018-06-26 11:47:56      阅读:225      评论:0      收藏:0      [点我收藏+]

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)

原型模式

原文:https://www.cnblogs.com/wskxy/p/9228272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!