单例模式

这一节是简单的单例模式,顾名思义也就是说一个类只能有一个对象。我们通过维护一个static的成员来记录这个唯一的对象实例。

把构造函数设为私有的,只能通过GetInstance来获得该类的实例

两种实现方法

 

class Singleton

{

public:

static Singleton* GetInstance()

{

static Singleton instance;

return &instance;

}

void method()

{

cout<<i++<<endl;

}

private:

Singleton()

:i(0){}

private:

int i;

};

//或者
class Singleton

{

public:

static Singleton* GetInstance()

{

if (!m_instance)

{

m_instance = new Singleton;

}

return m_instance;

}

void method()

{

cout<<i++<<endl;

}

private:

Singleton()

:i(0){}

private:

int i;

static Singleton* m_instance;

};

int _tmain(int argc, _TCHAR* argv[])

{

Singleton::GetInstance()->method();

Singleton::GetInstance()->method();

return 0;

}


 

 

全局变量可能进行多次实例化,而单例模式则是直接将其封死。

单例模式还是比较简单的,这里就不赘述了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值