求一个设计模式中单例的例子

解决方案 »

  1.   

    #include <iostream>
    using namespace std;
    //单例类的C++实现
    class Singleton
    {
    private:
    Singleton();//注意:构造方法私有
    virtual ~Singleton();
    static Singleton* instance;//惟一实例
    int var;//成员变量(用于测试)
    public:
    static Singleton* GetInstance();//工厂方法(用来获得实例)
    int getVar();//获得var的值
    void setVar(int);//设置var的值
    };
    //构造方法实现
    Singleton::Singleton()
    {
    this->var = 20;
    cout<<"Singleton Constructor"<<endl;
    }
    Singleton::~Singleton()
    {
    delete instance;
    }
    //初始化静态成员
    Singleton* Singleton::instance=new Singleton();
    Singleton* Singleton::GetInstance()
    {
    return instance;
    }
    //seter && getter含数
    int Singleton::getVar()
    {
    return this->var;
    }
    void Singleton::setVar(int var)
    {
    this->var = var;
    }
    //main
    int main(int argc, char* argv[])
    {
    Singleton *ton1 = Singleton::GetInstance();
    Singleton *ton2 = Singleton::GetInstance();
    cout<<"ton1 var = "<<ton1->getVar()<<endl;
    ton1->setVar(150);
    cout<<"ton2 var = "<<ton2->getVar()<<endl;
    return 0;
    }
      

  2.   

    /*
    设计模式例程
    根据有关例程综合而成
    */
    /*
    意图:
    提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 
    适用性:
    一个系统要独立于它的产品的创建、组合和表示时。 
    一个系统要由多个产品系列中的一个来配置时。 
    当你要强调一系列相关的产品对象的设计以便进行联合使用时。 
    当你提供一个产品类库,而只想显示它们的接口而不是实现时。  
    *//*
    MazeFactory <--------------------------------MazeGame ----> Maze
         | MapSite<----|
    BombedMazefactory | |
    EnchantedMazeFactory Door<---|
    MazePrototypeFactory Wall<---|
    Room<---|
    *//*
    */
    #include <iostream.h>
    #include "../public/MazeParts.H"
    #include "../public/MazeGame.H"
    #define MazeFactory_H/*
    */
    class MazeFactory {
    public:
        MazeFactory();
    /* {
    output("MazeFactory::MazeFactory()\n");
    };
    */
    /*
    */
        virtual Maze* MakeMaze() const;
    //        { return new Maze; }
        virtual Wall* MakeWall() const;
    //        { return new Wall; }
        virtual Room* MakeRoom(int n) const;
    //        { return new Room(n); }
        virtual Door* MakeDoor(Room* r1, Room* r2) const;
    //        { return new Door(r1, r2); }
    };
    /*
    */
    /* already maze.cppMaze* MazeGame::CreateMaze (MazeFactory& factory) {
        output("Maze* MazeGame::CreateMaze (MazeFactory& factory) \n");
        Maze* aMaze = factory.MakeMaze();
        Room* r1 = factory.MakeRoom(1);
        Room* r2 = factory.MakeRoom(2);
        Door* aDoor = factory.MakeDoor(r1, r2);    aMaze->AddRoom(r1);
        aMaze->AddRoom(r2); r1->SetSide(North, factory.MakeWall());
        r1->SetSide(East, aDoor);
        r1->SetSide(South, factory.MakeWall());
        r1->SetSide(West, factory.MakeWall()); r2->SetSide(North, factory.MakeWall());
        r2->SetSide(East, factory.MakeWall());
        r2->SetSide(South, factory.MakeWall());
        r2->SetSide(West, aDoor);    return aMaze;
    }
    *//*
    */
    class EnchantedMazeFactory : public MazeFactory {
    public:
        EnchantedMazeFactory();
    /*
    */
        virtual Room* MakeRoom(int n)  const{
    output("virtual Room* MakeRoom(int n)  const\n");
    return new EnchantedRoom(n, CastSpell());
    }
    /*
    */
        virtual Door* MakeDoor(Room* r1, Room* r2)  const{
    output("    virtual Door* MakeDoor(Room* r1, Room* r2)  const\n");
    return new DoorNeedingSpell(r1, r2); 
    }
    /*
    */
    protected:
        Spell* CastSpell() const;
    };
    /*
    */
    #define EnchantedMazeFactory_H
    #include "../public/MazeFactories.H"
    /*
    */
    /* already define maze.cpp
    Wall* BombedMazeFactory::MakeWall () const {
    output("Wall* BombedMazeFactory::MakeWall () const \n");
        return new BombedWall;
    }
    */
    /*
    */
    /*
    Room* BombedMazeFactory::MakeRoom(int n) const {
    output("Room* BombedMazeFactory::MakeRoom(int n) const {\n");
        return new RoomWithABomb(n);
    }
    */
    /*
    */
    void main() {
    /*
    */
    MazeGame game;
    BombedMazeFactory factory; game.CreateMaze(factory);
    /*
    */
    pause();
    }//*** the end
      

  3.   

    刚才的是abstract factory
    现在是singleton
    Singleton模式是常用的设计模式之一,但是要实现一个真正实用的设计模式却也不是件容易的事情。1.         标准的实现class Singleton 

    public: 
           static Singleton * Instance()        { 
                  if( 0== _instance) 
                  { 
                         _instance = new Singleton; 
                  } 
                  return _instance; 
           } 
    protected: 
           Singleton(void) 
           { 
           } 
           virtual ~Singleton(void) 
           { 
           } 
           static Singleton* _instance; 
    }; 
           这是教科书上使用的方法。看起来没有什么问题,其实包含很多的问题。下面我们一个一个的解决。2.         自动垃圾回收上面的程序必须记住在程序结束的时候,释放内存。为了让它自动的释放内存,我们引入auto_ptr改变它。
    #include <memory> 
    #include <iostream> 
    using namespace std; 
    class Singleton 

    public: 
           static Singleton * Instance() 
           { 
                  if( 0== _instance.get()) 
                  { 
                         _instance.reset( new Singleton); 
                  } 
                  return _instance.get(); 
           } 
    protected: 
           Singleton(void) 
           { 
                  cout <<"Create Singleton"<<endl; 
           } 
           virtual ~Singleton(void) 
           { 
                  cout << "Destroy Singleton"<<endl; 
           } 
           friend class auto_ptr<Singleton>; 
         static auto_ptr<Singleton> _instance; 
    }; 
    //Singleton.cpp
    auto_ptr<Singleton> Singleton::_instance; 3.         增加模板在我的一个工程中,有多个的Singleton类,对Singleton类,我都要实现上面这一切,这让我觉得烦死了。于是我想到了模板来完成这些重复的工作。现在我们要添加本文中最吸引人单件实现:/******************************************************************** 
        (c) 2003-2005 C2217 Studio 
        Module:    Singleton.h 
        Created:    9/3/2005   23:17 
        Purpose:    Implement singleton pattern 
       History: 
    *********************************************************************/ 
    #pragma once 
    #include <memory> 
    using namespace std; 
    using namespace C2217::Win32; 
    namespace C2217 

    namespace Pattern 

    template <class T> 
    class Singleton 

    public:
           static inline T* instance(); 
    private: 
           Singleton(void){} 
           ~Singleton(void){} 
           Singleton(const Singleton&){} 
           Singleton & operator= (const Singleton &){} 
           static auto_ptr<T> _instance; 
    }; 
    template <class T> 
    auto_ptr<T> Singleton<T>::_instance; 
    template <class T> 
     inline T* Singleton<T>::instance() 

           if( 0== _instance.get()) 
           { 
                  _instance.reset ( new T); 
           } 
           return _instance.get(); 

    //Class that will implement the singleton mode, 
    //must use the macro in it's delare file 
    #define DECLARE_SINGLETON_CLASS( type ) \ 
           friend class auto_ptr< type >;\ 
           friend class Singleton< type >; 


    4.         线程安全上面的程序可以适应单线程的程序。但是如果把它用到多线程的程序就会发生问题。主要的问题在于同时执行_instance.reset ( new T); 就会同时产生两个新的对象,然后马上释放一个,这跟Singleton模式的本意不符。所以,你需要更加安全的版本: 
    /******************************************************************** 
        (c) 2003-2005 C2217 Studio 
        Module:    Singleton.h 
        Author:     Yangjun D. 
        Created:    9/3/2005   23:17 
        Purpose:    Implement singleton pattern 
        History: 
    *********************************************************************/ 
    #pragma once 
    #include <memory> 
    using namespace std; 
    #include "Interlocked.h" 
    using namespace C2217::Win32; 
    namespace C2217 

    namespace Pattern

    template <class T> 
    class Singleton 

    public: 
           static inline T* instance(); 
    private: 
           Singleton(void){} 
           ~Singleton(void){} 
           Singleton(const Singleton&){} 
           Singleton & operator= (const Singleton &){} 
           static auto_ptr<T> _instance; 
           static CResGuard _rs; 
    }; 
    template <class T> 
    auto_ptr<T> Singleton<T>::_instance; 
    template <class T> 
    CResGuard Singleton<T>::_rs; 
    template <class T> 
     inline T* Singleton<T>::instance() 

           if( 0 == _instance.get() ) 
          { 
                  CResGuard::CGuard gd(_rs); 
                  if( 0== _instance.get()) 
                  { 
                         _instance.reset ( new T); 
                  } 
           } 
           return _instance.get();

    //Class that will implement the singleton mode, 
    //must use the macro in it's delare file 
    #define DECLARE_SINGLETON_CLASS( type ) \ 
           friend class auto_ptr< type >;\ 
           friend class Singleton< type >; 


           CresGuard 类主要的功能是线程访问同步,代码如下: 
    /****************************************************************************** 
    Module:  Interlocked.h 
    Notices: Copyright (c) 2000 Jeffrey Richter 
    ******************************************************************************/ 
    #pragma once 
    /////////////////////////////////////////////////////////////////////////////// 
    // Instances of this class will be accessed by multiple threads. So, 
    // all members of this class (except the constructor and destructor) 
    // must be thread-safe. 
    class CResGuard { 
    public: 
       CResGuard()  { m_lGrdCnt = 0; InitializeCriticalSection(&m_cs); } 
       ~CResGuard() { DeleteCriticalSection(&m_cs); } 
       // IsGuarded is used for debugging 
       BOOL IsGuarded() const { return(m_lGrdCnt > 0); } 
    public: 
       class CGuard { 
       public: 
          CGuard(CResGuard& rg) : m_rg(rg) { m_rg.Guard(); }; 
          ~CGuard() { m_rg.Unguard(); } 
       private: 
          CResGuard& m_rg; 
       }; 
    private: 
       void Guard()   { EnterCriticalSection(&m_cs); m_lGrdCnt++; } 
       void Unguard() { m_lGrdCnt--; LeaveCriticalSection(&m_cs); } 
       // Guard/Unguard can only be accessed by the nested CGuard class. 
       friend class CResGuard::CGuard; 
    private: 
       CRITICAL_SECTION m_cs; 
       long m_lGrdCnt;   // # of EnterCriticalSection calls 
    };/////////////////////////////////////////////////////////////////////////////// 5.         实用方法比如你有一个需要实现单件模式的类,就应该这样实现:
    #pragma once 
    #include "singleton.h" 
    using namespace C2217::Pattern; 
    class ServiceManger 

    public: 
           void Run() 
           { 
           } 
    private: 
           ServiceManger(void) 
           { 
           } 
           virtual ~ServiceManger(void) 
           { 
           } 
           DECLARE_SINGLETON_CLASS(ServiceManger); 
    }; 
    typedef Singleton<ServiceManger> SSManger; 
    在使用的时候很简单,跟一般的Singleton实现的方法没有什么不同。
    int _tmain(int argc, _TCHAR* argv[]) 

       SSManger::instance()->Run(); 

    一个简单的Singleton模式的实现,可以看到C++语言背后隐藏的丰富的语意,我希望有人能实现一个更好的Singleton让大家学习。我从一开始实现Singleton类的过程,其实就是我学习C++的过程,越是深入越觉得C++了不起。
      

  4.   

      using namespace std;
      class Single
      {
      private:
      static Single * p;
      public:
      static Single* getInstance();
      };
      Single * Single::p=0;
      Single* Single::getInstance()
      {
      if(p==0) p=new Single;
      return p;
      }
      

  5.   

    你们写的太麻烦了。class A
    {
     public:
        static A* Instance()
        {
            static A a;
            return &a;
        }
    };用的地方这么用就好了。A* pA = A::Instance();
    pA->func(...);