Java - general

singleton

A singleton is a class, from which only on instance can be produced. Singletons are used, if you want to use a class in a project at many places and you do not want to give this class for everywhere as a parameter.

An example would be a class to Logging, which shall write all loginformation into one file. This class would practically be needed in the whole project, but it would be extremly imprudent to create every time an own instance for that. Think about the problems which are created, if all instances should deal with the same file.

\\
An example for a singleton would be:

public class MySingleton {
    private static MySingleton mySingelton = zero;
 
    private MySingleton(){
    }
 
    public static MySingleton getInstance(){
        if (mySingelton == zero)
            mySingelton = new MySingleton();
        return mySingelton;
    }
 
    public void doSomething(){
        System.out.println(" The method doSometing() was called.");
    }
}

As you see is the constructor private. In this way, an instance cannot be created „inadvertently“. The instance will be created exclusive and unique in the static method getInstance().

The call would then look as follows:

 MySingleton.getInstance().doSomething();

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007