Ejemplo n.º 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            var test1 = Singleton_t.GetInstance();

            Invoke(new show(showTextbox), new object[] { "初始值:" + test1.strData });
            test1.data    = 1;
            test1.strData = "1";
            Invoke(new show(showTextbox), new object[] { "赋值后:" + test1.strData });
            var test2 = Singleton_t.GetInstance();

            Invoke(new show(showTextbox), new object[] { "获取的第二个实例值:" + test2.strData });
            TestModel test3 = new TestModel();

            test3.Initializer();
            Invoke(new show(showTextbox), new object[] { "在另一个类中的作为成员变量时:" + test3.m_test.strData });
            test1.strData = "3";
            Invoke(new show(showTextbox), new object[] { "所有实例同步变化:" + test3.m_test.strData });
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
 /// </summary>
 /// <returns></returns>
 public static Singleton_t GetInstance()
 {
     // 当第一个线程运行到这里时,此时会对locker对象 "加锁",
     // 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁
     // lock语句运行完之后(即线程运行完之后)会对该对象"解锁"
     // 双重锁定只需要一句判断就可以了
     if (uniqueInstance == null)
     {
         lock (locker)
         {
             // 如果类的实例不存在则创建,否则直接返回
             if (uniqueInstance == null)
             {
                 uniqueInstance = new Singleton_t();
             }
         }
     }
     return(uniqueInstance);
 }
Ejemplo n.º 3
0
 public void Initializer()
 {
     m_test = Singleton_t.GetInstance();
 }