大话设计模式之单例模式
来源:互联网 发布:十字锈软件 编辑:程序博客网 时间:2024/04/29 23:45
保证一个类仅有一个实例,,并提供一个访问它的全局访问点
//懒汉式class Singleton{ private static Singleton instance; private Singleton() {} public static Singleton GetInstance() { if (NULL == instance) { instance = new Singleton(); } return instance; }};
多线程时的单例模式:
//多线程情况下:class Singleton{ private static Singleton instance; //加一个锁 private static readonly object sync = new object(); private Singleton() {} public static Singleton GetInstance() { if (NULL == instance) //先判断是否存在,不存在再竞争 //之所以要这样,是为了防止每次调用都要涉及到锁,毕竟只实例化一次 { lock(sync) { if (NULL == instance) { instance = new Singleton(); } } } return instance; }};
单例模式分两类
一、在自己被加载时就将自己实例化,称为饿汉式单例类
类一加载就实例化对象,提前占用系统资源
//饿汉式public sealed class Singleton{ private static readonly Singleton instance = new Singleton(); private Singleton() {} public static Singleton GetInstance() { return instance; }};
二、在第一次被引用时才将自己实例化,称为懒汉式单例类
面临多线程访问的安全性问题, 即第一个程序那样
0 0
- 大话设计模式之单例模式
- 大话设计模式之单例模式
- 大话设计模式之单例模式
- 大话设计模式之单例模式
- 大话设计模式之单例模式
- 大话设计之单例模式
- 大话设计模式之单例模式(Singleton)
- 大话设计模式之___单例模式
- java设计模式大话之单例模式
- 《大话设计模式》java实现之单例模式
- 大话设计模式读书笔记之单例模式
- 《大话设计模式》--笔记(单例模式)
- 大话设计模式-单例模式
- 大话设计模式_单例模式
- 大话设计模式 单例模式
- 大话设计模式之一:单例模式
- 大话设计模式--单例模式
- 大话设计模式-单例模式
- linux内存管理之mmap
- sea.js 原理解析
- 给定一个正整数,找出一个数:与其二进制表示中1的个数相同,比该数小,而且最接近
- 【练习】面向对象系列(003)——奥特曼 PK 小怪兽
- 暂存 postgreSQL\MongoDB博客
- 大话设计模式之单例模式
- Makefile 关于realpath的研究
- 重建二叉树
- 面试心得
- android不同activity之间传送数据值得方法
- Exchange Server2013 系列九:常规配置
- C++ 虚函数解析
- 【LeetCode刷题记录】Reverse Bits
- Django+Markdown2+bootstrap+google-code-prettify