设计模式:创建型模式:单例模式(singleton pattern)

8 篇文章 0 订阅

下面的内容主要来自于了

1)深入浅出设计模式 by AI92

2)http://www.jellythink.com/archives/82 (这篇讲的特别深)


单例模式的目的:

保证一个类有且仅有一个对象,并提供一个访问这个对象的全局访问点。

通常单例模式适合用于表示具有唯一性的对象,比如文件系统、资源管理器等。


单例模式的实现方法:

为了限制创建对象的个数,而且要让这个类不能被继承,构造函数必须被定义为private以避免其他类创建这个类的对象;

同时为了保证这个类有用,必须产生一个对象(不然就没用了不是。。。),而且同时必须要提供一个访问该对象的静态方法。

所以结论是,客户必须通过调用类的方法来获得这个类的唯一对象的访问。



这个实现中,类的构造函数是私有的,所以我们无法在外部通过构造函数来创建类的对象。

唯一的对象是在类第一次被运行时创建的,特别要强调的是关键字static的运用:

1)static data member (比如上面代码中的m_Instance)

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

2)static function member (比如上面代码中的GetInstance, DestoryInstance)

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.


具体见http://www.tutorialspoint.com/cplusplus/cpp_static_members.htm



但是上图这个实现虽然简单,但是还是有不少问题的,详见http://www.jellythink.com/archives/82 的介绍,主要是考虑两个问题:多线程和对象的销毁


感慨:

全是static 其实就是套了个class马甲的全局变量

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值