设计模式--单例模式Singleton

单例模式是使用最广泛的设计模式之一。顾名思义,单例就是一个类只有一个实例。为什么会要求一个实例呢?一个原因是一个实例能够满足需求,过多实例的存在只会耗费系统资源;另一个原因是为了数据保持一致,多个实例导致数据状态不一致。
实际上,定义一个全局的实例,也算是单例,但无法限制用户再去定义多个。规范的接口定义,有利于限制实例的定义。例如下图中,类的构造函数被私有化,用户就只能通过GetInstance()接口得到实例。

UML类图

这里写图片描述

代码实例

C++的代码实例如下所示,这是一个简单的例子,如果在多线程的环境下,是需要加锁控制的。

Singleton.h

#ifndef __SINGLETON_H_
#define __SINGLETON_H_


class Singleton
{
public:
    static Singleton * GetInstance();
    static void DestroyInstance();

private:
    Singleton();

    static Singleton* m_instance;
};

#endif

Singleton.cpp

#include <iostream>
#include "Singleton.h"

using namespace std;


Singleton* Singleton::m_instance = NULL;

Singleton::Singleton()
{
    cout<<"Singleton Constructor"<<endl;

}


Singleton* Singleton::GetInstance()
{

    if (m_instance == NULL)
    {
        m_instance = new Singleton();
    }

    return m_instance;
}


void Singleton::DestroyInstance()
{
    if (m_instance != NULL)
    {
        delete m_instance;
    }

}

main.cpp

#include <iostream>
#include "Singleton.h"


using namespace std;


int main()
{
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();

    if (s1 == s2)
    {
        cout<<"The same"<<endl;
    }

    Singleton::DestroyInstance();

    return 0;
}

更多C++单例可参考
http://blog.csdn.net/hackbuteer1/article/details/7460019

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值