Home>

C++ implementation of singleton pattern of design pattern

First, the classic implementation (non-thread-safe)

class singleton
{
  public:
    static singleton * getinstance ();
  protected:
    singleton () {}
  private:
    static singleton * p;
};
singleton * singleton ::p=null;
singleton * singleton ::getinstance ()
{
  if (null == p)
    p=new singleton ();
  return p;
}

Second, the lazy mode and the hungry mode

Sloth:So the name implies,Classes will not be instantiated without a last resort,That is to say, the instantiation of the class instance is not instantiated for the first time.So the classic method above is classified as a lazy implementation;

Hungry man:When you are hungry, you must eat hungry.So instantiate when the singleton class is defined.

Features and options

Because of thread synchronization,So the traffic is relatively large,Or when there may be more threads accessed,Implemented with hungry guys,Can achieve better performance.This trades space for time.When there are fewer visits,Use lazy people to achieve.This is time for space.

Thread-safe lazy mode

1. Lock to achieve thread-safe lazy mode

class singleton
{
  public:
    static pthread_mutex_t mutex;
    static singleton * getinstance ();
  protected:
    singleton ()
    {
      pthread_mutex_init (&mutex);
    }
  private:
    static singleton * p;
};
pthread_mutex_t singleton ::mutex;
singleton * singleton ::p=null;
singleton * singleton ::getinstance ()
{
  if (null == p)
  {
    pthread_mutex_lock (&​​mutex);
    if (null == p)
      p=new singleton ();
    pthread_mutex_unlock (&​​mutex);
  }
  return p;
}

2. Internal static variables to achieve lazy mode

class singleton
{
  public:
  static pthread_mutex_t mutex;
  static singleton * getinstance ();
  protected:
    singleton ()
    {
      pthread_mutex_init (&mutex);
    }
};
pthread_mutex_t singleton ::mutex;
singleton * singleton ::getinstance ()
{
  pthread_mutex_lock (&​​mutex);
  static singleton obj;
  pthread_mutex_unlock (&​​mutex);
  return&obj;
}

Hungry mode (thread-safe in itself)

class singleton
{
  public:
    static singleton * getinstance ();
  protected:
    singleton () {}
  private:
    static singleton * p;
};
singleton * singleton ::p=new singleton;
singleton * singleton ::getinstance ()
{
  return p;
}
c
  • Previous Three ways SpringMVC returns json data
  • Next C # custom DataGridViewColumn showing TreeView