• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
bobird的学习笔记
博客园    首页    新随笔    联系   管理    订阅  订阅
.net FramkWork Singleton 设计模式
sealed class Singleton
{
       private Singleton();
       public static readonly Singleton Instance=new Singleton();
}

方法一:

using System;  
namespace csPattern.Singleton  
{  
public class Singleton  
{  
static Singleton uniSingleton = new Singleton();  
private Singleton() {}  
static public Singleton instance()  
{  
return uniSingleton;  
}  
}  
}  

using System;  
namespace csPattern.Singleton  
{  
public class Singleton  
{  
static Singleton uniSingleton;  
private Singleton() {}  
static public Singleton instance()  
{  
if (null == uniSingleton)  
{  
uniSingleton = new Singleton _lazy();  
}  
return uniSingleton;  
}  
}  
}  

C#使用Singleton模式的实现有两个技巧:一是使用静态成员变量保存“全局”的实例,确保了唯一性,使用静态的成员方法instance() 代替 new关键字来获取该类的实例,达到全局可见的效果。二是将构造方法设置成为private,如果使用new关键字创建类的实例,则编译报错,以防编程时候笔误。

文章出处

 

posted on 2013-01-14 15:12  bobird  阅读(150)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3