首页 > 其他 > 详细

单体模式

时间:2015-05-10 00:49:57      阅读:218      评论:0      收藏:0      [点我收藏+]
#include<iostream.h>
class A
{
private:
    int a;
    A(int x);//将构造函数定义为私有,因此我们只能通过后面的create静态函数来创建A实例
    static A* instance;
public:
    static A *create(int x)//单体模式,以保证程序最多创建一个A实例
    {
        if(!instance)
        {
            instance=new A(x);
        }
        return instance;
    }
    int get()
    {
        return a;
    }

};
A* A::instance=NULL;
A::A(int x)
{
    a=x;
}
void main()
{
    A *ptr;
    ptr=A::create(2);
    cout<<ptr->get();//输出2
}
    

 

单体模式

原文:http://www.cnblogs.com/leijiangtao/p/4491555.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!