单例模式

View Code
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //Earth e1 = new Earth();
 6             //Earth e2 = new Earth();
 7             Earth earth = Earth.GetEarth();
 8             Earth earth2 = Earth.GetEarth();
 9             Console.WriteLine(
10                 object.ReferenceEquals(earth,earth2));
11             Console.ReadKey();
12         }
13     }
14 
15     sealed class Earth
16     {
17         //static的赋值语句值运行一次(在类第一次加载的时候)
18         //只运行一次
19         private static Earth instance = new Earth();
20 
21         public static Earth GetEarth()
22         {
23             //return new Earth();
24             return instance;
25         }
26 
27         //1、把构造函数private。(防止外部调用构造函数创建对象)
28         //2、声明一个静态的字段,初始化一个实例。(提供对象的唯一实例)
29         //3、编写一个静态方法或者静态属性,返回那个唯一的实例
30         private Earth()
31         {
32         }
33         public int Population { get; set; }
34     }

 扩展阅读:

–http://blog.csdn.net/wanghao72214/archive/2009/04/02/4042607.aspx
–http://www.cnblogs.com/aspnet2008/archive/2008/05/09/1190328.html
–http://tianli.blog.51cto.com/190322/43743
 
posted @ 2013-03-16 20:20  Big.Eagle  阅读(76)  评论(0)    收藏  举报