设计模式 -- 单例模式(Singleton)

单例模式

Singleton模式解决问题十分常见而且比较简单。那么什么是单例模式呢?其实就是创建一个唯一的类对象,内存中只占有一份。那么问题来了,要怎么创建一个唯一对象呢?当然,直接定义一个全局的对象可以实现,但在有些纯粹的面向对象语言中,如C#,jave中,就不能定义全局变量了。那么,除了全局变量还有什么是唯一性的呢?恩,没错,就是static静态变量。我们的单例模式就是通过一个静态的类成员函数实现的(创建对象)。

单例模式类对象是一个共享对象,内存中只有一份,节约了内存。它常常和工厂模式一起使用,因为工厂对象只需唯一一个就够了。

结构示意图:(一个static方法 + 一个对象指针)
这里写图片描述

示例代码

#ifndef __DesignMode__Singleton__
#define __DesignMode__Singleton__

#include <iostream>
using namespace std;

class Singleton
{
public:
    static Singleton * Instance();

protected:
    Singleton();

private:
    static Singleton* _instance;
};

#endif /* defined(__DesignMode__Singleton__) */
#include "Singleton.h"
#include <iostream>
using namespace std;

Singleton* Singleton::_instance = 0;

Singleton::Singleton()
{
    cout << "Singleton create ..." << endl;
}

Singleton* Singleton::Instance()
{
    if (_instance == 0)
    {
        _instance = new Singleton();
    }

    return _instance;
}

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

int main(int argc,char* argv[])
{
    Singleton* sgn1 = Singleton::Instance();
    Singleton* sgn2 = Singleton::Instance();
    Singleton* sgn3 = Singleton::Instance();

    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值