天天看点

设计模式 笔记 单例模式 Singleton

//---------------------------15/04/09----------------------------

//Singleton 单例模式-----对象创建型模式

//这样实现是有线程安全问题的

class Singleton

{

public:

   static Singleton* Instance();

protected:

    Singleton();

private:

   static Singleton* _instance;

};

Singleton* Singleton::_instance =0;

Singleton* Singleton::Instance()

{

   if(_instance == 0)

        _instance =new Singleton;

   return _instance;

}

//      2>创建Singleton类的子类:

//        使用单件注册表:

class Singleton

{

public:

   static void Register(constchar* name, Singleton*);

   static Singleton* Instance();

protected:

   static Singleton* Lookup(constchar* name);

private:

   static Singleton* _instance;

   static map<char*,Singleton*> _registry;//感觉map更好用

};

Singleton* Singleton::Instance()

{

   if(_instance == 0)

    {

       const char* singletonName = getenv("SINGLETON");

        _instance = Lookup(singletonName);

    }

   return _instance;

}

//子类注册:在构造函数中注册自己

MySingleton::MySingleton()

{

    Singleton::Register("MySingleton",this);

}

//这个构造函数只有被调用了,注册表中才有MySingleton,所以要在实现文件中定义一个静态实例

static MySingleton theSingleton;

//  9:代码示例:

class MazeFactory

{

public:

   static MazeFactory* Instance();

   static void Register(constchar* name, MazeFactory*);

protected:

    MazeFactory();

   static MazeFactory* Lookup(constchar* name);

private:

   static MazeFactory* _instance;

   static map<char*,MazeFactory*> _registry;

};

MazeFactory* MazeFactory::_instance =0;

MazeFactory* MazeFactory::Instance()

{

   if(_instance = 0)

    {

       const char* mazeName = getenv("MAZESTYLE");

        _instance = Lookup(mazeName);

    }

   return _instance;

}

void MazeFactory::Register(constchar* name, MazeFactory*  fac)

{

    _registry.insert(std::make_pair(name,fac));

}

MazeFactory* MazeFactory::Lookup(constchar* name)

{

    map<char*,MazeFactory*>::iterator it=_registry.find(name);

   if(it != _registry.end())

       return it->second;

   return 0;

}