Blog do projektu Open Source JavaHotel

czwartek, 22 października 2009

Singleton without private constructor and static getInstance metod

Create SingletonFactory class. This class is the owner of the one Singleton instance. Add also a static switch "already created" and use this switch in constructor (public) to break the second and next Singleton initialization.

Code snippet below:

singleton.h 
#include <iostream

class Singleton {
public:
  Singleton() {
     if (exists_already) {
        std::cout << "You mustn't do that !" << std::endl;
        // failure action !!!
     }
     else {
       std::cout << "Singleton first init" << std::endl;
       exists_already = true;
     }
  }

  void singleAction() {
     std::cout << "Run single action" << std::endl;
  }

private:
  static bool exists_already;
};

SingleFactory.h
#include <singleton.h>

class SingleFactory {

  public:
    static Singleton *getInstance() {
      return &single;
    }

  private:
    static Singleton single;
};

SingleFactory.cpp
(pay attention that it keeps movables belonging to Singleton class)

#include <singlefactory.h>

Singleton SingleFactory::single;
bool Singleton::exists_already = false;

and finally the usage example
main.cpp

include <iostream>
#include <cstdlib>
#include <singlefactory.h>

using namespace std;

int main(int argc, char *argv[])
{
  Singleton *n = SingleFactory::getInstance();
  cout << "Hello, world!" << endl;
  n->singleAction();
  Singleton *nextS = new Singleton();
  Singleton singleS;


  return EXIT_SUCCESS;
}

Brak komentarzy:

Prześlij komentarz