.net 单例模式
时间:2011-02-24 来源:chongyang
理解:在类中封装了唯一一个类的实例,构造函数为私有的,不允许类外创建实例。
代码:

1 public class Student参考:http://hi.baidu.com/mingyue091221/blog/item/d53574c8c4267a8dc8176843.html
2 {
3 private static Student stu;
4 private static object _obj= new object();
5 private Student(){};
6 public static Instance()
7 {
8 if(stu==null)
9 {
10 lock(_obj) //锁定代码区
11 {
12 if(stu==null)
13 {
14 stu = new Student();
15 }
16 }
17 }
18 return stu;
19 }
20 }
21
22 public class Test
23 {
24 void Main(string[] args)
25 {
26 Student stu1 = Student.Instance();
27 Student stu2 = Student.Instance();
28 if (stu1.Equals(stu2))
29 {
30 Console.WriteLine("是同一个对象的引用");
31 }
32 else
33 {
34 Console.WriteLine("是两个不同的对象的引用");
35 }
36 }
37 }
相关阅读 更多 +
排行榜 更多 +

<img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748214895997494.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748214895997494.png" alt="机器人狙击手最新版" />
飞行射击 下载
<img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748213241693464.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748213241693464.png" alt="我的枪有子弹最新版" />
飞行射击 下载- 4 <img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0525/1748174029364713.jpg" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0525/1748174029364713.jpg" alt="战斗地带汉化版" />下载58.6 MB · 90℃
1970-01-01
- 5 <img preview="http://pic.pdowncc.com/uploadimg/img/2025/0526/1748208215706549.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/img/2025/0526/1748208215706549.png" alt="超级兔子人联机版手机版" />下载45.51 MB · 94℃
1970-01-01
- 6 <img preview="http://pic.pdowncc.com/uploadimg/img/2025/0526/1748208215706549.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/img/2025/0526/1748208215706549.png" alt="超级兔子人联机版手机版" />下载169.80 MB · 99℃
1970-01-01