我与C++设计模式(二)——单例模式

单例模式应该是我接触设计模式时最早学会的一个设计模式,它比较简单易懂,目的就一个,设计出能只能创建一个对象的类。

上代码:

singleton.h

<span style="font-size:14px;">//singleton.h

#ifndef _SINGLETON_H__
#define _SINGLETON_H__

#include <iostream>

class singleton
{
        private:
                static singleton *_instance;
        public:
                static  singleton *Instance();
        protected:
                singleton();
};

#endif //_SINGLETON_H__
</span>

singleton.cpp

<span style="font-size:14px;">//singleton.cpp

#include "singleton.h"

using namespace std;

singleton *singleton::_instance = 0;

singleton::singleton()
{
        cout<<"singleton created!"<<endl;
}

singleton *singleton::Instance()
{
        if (_instance == 0)
                _instance = new singleton();
        return _instance;
}
</span>

main.cpp

<span style="font-size:14px;">//main.cpp

#include "singleton.h"

int main(int argc, char **argv)
{
        singleton *pOne = singleton::Instance();
}
</span>
关键技术在于将singleton类的构造函数不公开,而是通过一个静态函数去调用构造函数,这样构造函数就成为透明的了,设计者能够通过一个静态函数来操控它,比如,用另个一个静态成员属性来计数,client只能得到singleton的静态函数这个唯一的接口。

本模式的UML图比较简单,暂不给出。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值