6.对象创建型模式-单件模式

  单件模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

  单件模式实现:1.类方法Instance()提供访问实例的全局访问点。2.类构造函数声明为protected,防止直接实例化类的对象。

将抽象工厂实现为单件的一种简单方式,客户通过Instance接口获取唯一实例:

/* 实现为单件的抽象工厂类 */ 
class MazeFactory {
public:
    static MazeFactory* Instance();
    
    //existing interface goes here
protected: 
    MazeFactory();/* 构造方法为保护,避免直接创建对象 */     
    
private:
    static MazeFactory* _instance;
};

MazeFactory* MazeFactory::_instance = 0;

/* 唯一实例的全局访问点 */ 
MazeFactory* MazeFactory::Instance () {
    if (MazeFactory == 0) {
        _instance = new MazeFactory;
    }
    return _instance;
}

当单件类Singleton存在多个子类时,可以采用单件注册表的方式实现:

/* 单件类 */
class Singleton {
public:
    static void Register(const char* name, Singleton* );/* 注册单件实例 */
    static Singleton* Instance();/* 获取单件实例的全局访问点 */ 

protectedstatic Singleton* Lookup(const char* name);

private:
    static Singleton* _instance;        
    static List<NameSingletonPair>* _registry;/* 单件注册表 */             
};

/* 单件实例全局访问点的实现:通过查_redistry表获取合适的单件实例 */ Singleton* Singleton::Instance () { if (_instance == 0) { /* 使用环境变量来提供单件实例的名字,也可以参数化Instance方法 */ const char* singletonName = getenv("SINGLETON"); _instance = Lookup(singletonName); } return _instance; }

/* MySingleton类注册自己,可以在类的构造器中 */ MySingleton::MySingleton() { Singleton::Register("MySingleton", this); }

/* 客户在定义单件类的文件中,使用static关键字实例化单件类,使得实例化的对象在文件外部不可见 */ static MySingleton theSingleton;
原文地址:https://www.cnblogs.com/VincentXu/p/3348635.html