1 ///<summary>
2 /// Sigleton模式简单实例
3 ///</summary>
4 class Program
5 {
6 staticvoid Main(string[] args)
7 {
8 string _title;
9 //调用者不可以通过new的形式得到Singleton的实例
10 LogWriter log = LogWriter.GetInstance();
11 log.ddd();
12 //调用LogWriter中的静态字段(外部类的类类型,只能通过类型访问而不能通过实例访问)
13 _title = LogWriter._boss.Title;
14 LogWriter._boss.SayHi();
15 Console.WriteLine(_title);
16 Console.ReadLine();
17 }
18 #region LogWriter描述
19 publicclass LogWriter
20 {
21 //声明一个静态变量,类型为类本身
22 privatestatic LogWriter _instance =null;
23 //声明一个静态变量,类型为一外部类
24 publicstatic Boss _boss =new Boss();//注意此处必须初始化,否则,调用会报错:{未将引用添加到实例}
25 //将类的构造函数私有化,使得这个类不可以被外界创建
26 private LogWriter()
27 {
28 }
29 //提供静态的方法创建类的实例
30 publicstatic LogWriter GetInstance()
31 {
32 if(_instance ==null)
33 {
34 _instance =new LogWriter();
35 }
36 return _instance;
37 }
38 publicvoid ddd()
39 {
40 Console.WriteLine("hi!");
41 }
42 }
43 #endregion
44
45 #region Boss描述
46 publicclass Boss
47 {
48 privatestring _Title;
49
50 publicstring Title
51 {
52 get { return _Title; }
53 set { _Title = value; }
54 }
55
56 public Boss()
57 {
58 this._Title ="Lucky";
59 }
60 publicvoid SayHi()
61 {
62 Console.WriteLine("Hello,World!");
63 }
64 }
65 #endregion
66 }