• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
gooliugle
博客园    首页    新随笔    联系   管理    订阅  订阅
大话设计模式读书笔记17----单例模式(Singleton)

单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1、多线程:lock是确保一个线程在临界区,另一个线程不能进入临界区。如果其他线程试图进入锁定的代码,它将一直等待。

代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace Singleton
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             Singleton s1 = Singleton.GetInstance();
12             Singleton s2 = Singleton.GetInstance();
13             if (s1 == s2)
14             {
15                 Console.WriteLine("两个对象相同");
16             }
17         }
18     }
19     class Singleton
20     {
21         private static Singleton instance;
22         private static readonly object syncRoot = new object();
23         private Singleton()
24         {
25  
26         }
27         public static Singleton GetInstance()
28         {
29             lock (syncRoot)
30             {
31                 if(instance==null)
32                 {
33                     instance = new Singleton();
34                 }
35             }
36             return instance;
37         }
38     }
39 }

2、双重锁定

代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace Singleton
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             Singleton s1 = Singleton.GetInstance();
12             Singleton s2 = Singleton.GetInstance();
13             if (s1 == s2)
14             {
15                 Console.WriteLine("两个对象相同");
16             }
17         }
18     }
19     class Singleton
20     {
21         private static Singleton instance;
22         private static readonly object syncRoot = new object();
23         private Singleton()
24         {
25  
26         }
27         public static Singleton GetInstance()
28         {
29             if (instance == null)
30             {
31                 lock (syncRoot)
32                 {
33                     if (instance == null)
34                     {
35                         instance = new Singleton();
36                     }
37                 }
38             }
39             return instance;
40         }
41     }
42 }


 

 

posted on 2010-05-15 14:02  gooliugle  阅读(359)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3