using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace WindowsFormsapplication5{ class Class1 { PRivate static Class1 mInstance; //线程辅助对象 private static readonly object lockAssistant = new object(); /// <summary> /// 单例 /// </summary> /// <returns></returns> public static Class1 Instance { get { if (mInstance == null) { lock (lockAssistant) { if (mInstance == null) { mInstance = new Class1(); } } } return mInstance; } } public int dd() { return 1; } public int cc() { return 2; } }}
用下面的代码调用上面的类,自己调试下:就可以掌握单例模式的精髓了
int a= Class1.Instance.cc() + Class1.Instance.dd();
MessageBox.Show(a.ToString());
喜欢的给我点歌赞哦
新闻热点
疑难解答