文章标题
来源:互联网 发布:网络实用技术基础作业2 编辑:程序博客网 时间:2024/06/16 18:20
转载注明出处:http://blog.csdn.net/qq_33536981/article/details/78603892
创建型模式一:单例模式
单例模式是一种非常常见的模式,当我们会长期用到某一对象,或者希望整个程序只创建一个对象的时候就可以使用单例模式。
单例模式又分懒汉试和饿汉试
懒汉试
class SingleOne//懒汉试{private: static SingleOne * m_single; SingleOne() { cout << "begin" << endl; }public: static SingleOne *getInstance() { if (m_single == NULL) { m_single = new SingleOne(); } return m_single; } static void removeInstance() { if (m_single != NULL) { delete (m_single); m_single = NULL; } } void print(char *str) { cout << str << endl; }};SingleOne *SingleOne::m_single = NULL;
饿汉试
class SingleTow//懒汉试{private: static SingleTow *m_single; SingleTow() { cout << "begin2" << endl; }public: static SingleTow *getInstance() { return m_single; } static void removeInstance() { if (m_single != NULL) { delete (m_single); m_single = NULL; } } void print(char *str) { cout << str << endl; }};SingleTow *SingleTow::m_single = new SingleTow();
注意饿汉试初始化一定要在外部初始化,这样才能分配内存,不然编译器不会分配内存。
懒汉试在多线程的时候会有问题,因为不能多线程同步了。
比如,A在getInstance时,有可以这个时间有点长,B也在getInstance,这个时候当他们同时完成了就会创建两个对象,这就不满足单例模式的原则就会出现很多错误。饿汉试就不会有这个问题,因为不管你用不用,他都已经创建了。
改进:
static CCriticalSection cs;class SingleTest{private: static SingleTest *m_single; SingleTest() { cout << "begin" << endl; }public: static SingleTest *getInstance() { if (m_single == NULL)//这里很重要,如果对象不为空,就不要加锁解锁浪费时间 { cs.lock(); if (m_single == NULL) { m_single = new SingleTest(); } cs.unlock(); } return m_single; } void print() { cout << "vailing" << endl; }};SingleTest *SingleTest::m_single = NULL;
阅读全文
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 浅谈LCD、OLED、TFT取模及其程序开发的算法取舍
- xlrd我常用的命令
- es6相关
- Apache Spark 2.2.0 中文文档
- fast r cnn 论文疑惑解答
- 文章标题
- DSS 代码分析【BufferWindow实现】
- leetcode 14 Longest Common Prefix
- Qt之QSS(样式表语法)【转】
- Linux ftp 命令
- alpha版、beta版、rc版的意思
- bzoj2049 洞穴勘探【LCT模板】
- stm32L011寄存器操作flash
- ES笔记