设计模式之——单例

单例模式是最常用的模式,在做项目的时候每个系统基本都是单例。

保证在整个生命周期,只存在一个该实例的对象。
应有场景:在逻辑上在系统中该类只存在一个实例。比如:一个系统中可以存在有多个打印任务,但是正在运行的任务只有一个。游戏的场景管理类,时间管理类等等。
代码示例:

code example here:
        class Singleton
        {
            private: 
                static Singleton *instance ;
                int i;
                Singleton(int x):int(x){}//私有化构造函数
                Singleton(const Singleton&);//私有化复制构造函数,放置复制
            public:
                Singleton* instance()
                {
                    if(NULL == instance)
                    {
                        instance = new Singleton(0);
                    }
                    return instance;
                }
                int GetValue(){ reutrn i;}
                void SetValue(const int& x){i = x;}
        }
        Singleton* Singleton::instance = NULL;

The End~~

猜你喜欢

转载自blog.csdn.net/coderling/article/details/52940073