希望有且只有一个类的实列返回给调用程序时,就可以使用单元素模式(singleton pattern):
class TheOnlyInstance
{
public:
static TheOnlyInstance * GetTheOnlyInstance();
protected:
TheOnlyInstance(){}
};
通过 把构造函数声明为protected,并去掉公有构造。防止局部实例被创建。
TheOnlyInstance the; // not allowed
只能通过公有静态方法GetTheOnlyInstance 来访问类。
通过 把构造函数声明为protected,并去掉公有构造。防止局部实例被创建。
TheOnlyInstance * TheOnlyInstance : GetTheOnlyInstance()
{
static TheOnlyInstance obj;
return &obj;
}
检索指向这个类的指针,只需要调用GetTheOnlyInstance()
TheOnlyInstance* pTheOnlyInstance = TheOnlyInstance: GetTheOnlyInstance();