CSC/ECE 517 Fall 2010/ch3 3f DF: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 13: Line 13:
class MySingleton
class MySingleton
{
{
public:
  public:
static MySingleton* Instance()
    static MySingleton* Instance()
{
    {
if(s_pSingletonObject == NULL)
      if(s_pSingletonObject == NULL)
s_pSingletonObject = new MySingleton;
        s_pSingletonObject = new MySingleton;
return s_pSingletonObject;
      return s_pSingletonObject;
}
    }
static void Destroy()
    static void Destroy()
{
    {
if(s_pSingletonObject != NULL)
      if(s_pSingletonObject != NULL)
{
      {
delete s_pSingletonObject;
        delete s_pSingletonObject;
s_pSingletonObject = NULL;
        s_pSingletonObject = NULL;
}
      }
}
    }
private:
  private:
//Direct access to the constructor/destructor is prohibited
  //Direct access to the constructor/destructor is prohibited
MySingleton() {}
  MySingleton() {}
virtual ~MySingleton() {}
  virtual ~MySingleton() {}
static MySingleton* s_pSingletonObject;
  static MySingleton* s_pSingletonObject;
};
};
</pre>
</pre>

Revision as of 05:34, 4 October 2010

The Singleton pattern in static and dynamic languages


Introduction

Text overview

UML Diagram

Static Language Implementation

class MySingleton
{
  public:
    static MySingleton* Instance()
    {
      if(s_pSingletonObject == NULL)
        s_pSingletonObject = new MySingleton;
				
      return s_pSingletonObject;
    }
		
    static void Destroy()
    {
      if(s_pSingletonObject != NULL)
      {
        delete s_pSingletonObject;
        s_pSingletonObject = NULL;
      }
    }
		
  private:
  //Direct access to the constructor/destructor is prohibited
  MySingleton() {}
  virtual ~MySingleton() {}
		
  static MySingleton* s_pSingletonObject;
};

Dynamic Language Implementation

Ruby Sample code here

References