tags:

views:

136

answers:

4
+1  Q: 

singleton class

Possible Duplicates:
Singletons: good design or a crutch?
Problems with Singleton Pattern
Singleton: How should it be used

Hi.. Please help me up to understand what is the use of singleton class

Thank you

+3  A: 

The purpose of the singleton pattern is to ensure that only one instance of a class ever exists. This is achieved by making the constructor for the class private and forcing clients to access the instance via a static member function, often just called instance, which is responsible for creating and managing the single instance.

In the general case, singletons are really an anti-pattern and should not be used.

James McNellis
+2  A: 

A singleton class is designed to control the creation of instances of that class so that only one such instance can be created.

e.g.

class Singleton {
    public:
        static void createInstance() { instance = new Singleton(); }
        static Singleton& getInstance() { return *instance; }
        int getValue() { return value; }

    private:
        Singleton() { value = 4; }
        int value;

        static Singleton *instance;
};

...

Singleton.createInstance();
int x = Singleton.getInstance().getValue();
brennie
A: 

One example of Singleton class is Think you have a memory map and a calss to create and write info to the memory map. To avoid the inheriting or containing classes to create multiple instances we can go for this singleton approach.

Raghuram
Because it is impossible to have more than one map at a time?
jalf
I meant that avoiding mutile copies of same memory map inside the same process.
Raghuram
A: 

Singleton is a design pattern used to control the number of instantiations of a class, usually only one.

class Singleton
{
  private:
    Singleton() {} // the constructor is private, so non reachable from outside the class 

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

The example code lets you create only one instance of Singleton. Like James already wrote, Singletons often produce more problems than they solve. Another good article about singltons can be found here

Holger Kretzschmar
if it limits the number of instantiations to more than one, it's not a singleton. Hence the **single** part of the name.
jalf