设计模式--单例模式C++实现

一般情况下,我们建立的一些类是属于工具性质的,基本不用存储太多的跟自身有关的数据,在这种情况下,我们只需要一个实例对象就可以。
如果采用全局或者静态变量的方式,会影响封装性,难以保证别的代码不会对全局变量造成影响。

考虑到这些需要,我们将默认的构造函数声明为私有的,这样就不会被外部所new了,甚至可以将析构函数也声明为私有的,这样就只有自己能够删除自己了。在Java和C#这样纯的面向对象的语言中,单例模式非常好实现,直接就可以在静态区初始化instance,然后通过getInstance返回,这种就被称为饿汉式单例类。也有些写法是在getInstance中new instance然后返回,这种就被称为懒汉式单例类,但这涉及到第一次getInstance的一个判断问题。
Singleton* getInstance()
{
    if (instance == NULL)
        instance = new Singleton(); 
    return instance;
}
但是在多线程的环境下却不行了,因为很可能两个线程同时运行到if (instance == NULL)这一句,导致可能会产生两个实例。于是就要在代码中加锁。
Singleton* getInstance()
{
    lock();
    if (instance == NULL)
    {
       instance = new Singleton();
    }
    unlock();

    return instance;
}
但这样写的话,会稍稍映像性能,因为每次判断是否为空都需要被锁定,如果有很多线程的话,就爱会造成大量线程的阻塞。
还有一种是饿汉模式
1.懒汉式是以时间换空间的方式。
2.饿汉式是以空间换时间的方式。
饿汉模式代码如下:

// Singleton.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <tchar.h>
#include <iostream>
using namespace std;

class singleton
{
protected:
		singleton(){}
private:
		static singleton* p;
public:
		static singleton* initance();
};
singleton* singleton::p = new singleton;
singleton* singleton::initance()
{
		return p;
}


int _tmain(int argc, _TCHAR* argv[])
{
	singleton* singleton1 = singleton::initance();
	singleton* singleton2 = singleton::initance();
	if (singleton1 == singleton2)
	{
		cout<<"singleton1 = singleton2"<<endl;
	}
	system("pause");
	cin.get();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/nicholas_dlut/article/details/88058407