单例模式

单例模板类

namespace test {
    template
    class Singleton {
    private:
        static T *instance_;
    protected:
        Singleton() {}
        virtual ~Singleton() {}
    public:
        static bool InitInstance() {
            if (NULL != instance_) return false;
            instance_ = new T;
            return true;
        }

        template static bool InitInstance(ARG_TYPE nArg) {
            if (NULL != instance_) return false;
            instance_ = new CLS_TYPE(nArg);
            return true;
        }

        static bool ExitInstance() {
            if (NULL == instance_) return false;
            delete instance_;
            instance_ = NULL;
            return true;
        }

        inline static T *GetInstance() {
            return instance_;
        }

        inline static T &Instance() {
            assert(NULL != instance_);
            return *instance_;
        }

        template inline static CLS_TYPE *GetSubInstance() {
            if (NULL == instance_) {
                return NULL;
            }
            return dynamic_cast(instance_);
        }

        template inline static CLS_TYPE &SubInstance() {
            assert(NULL != instance_);
            return *dynamic_cast(instance_);
        }
    };
    template T *test::Singleton::instance_ = NULL;
} // namespace test

继承使用

namespace test{
  class A: public test::Singleton {
        friend class test::Singleton;
  private:
        A();
        ~A();
  }
}

int main(int argc, char *argv[]){
        test::A::InitInstance();
}

你可能感兴趣的:(单例模式)