Menu
Topics Index
...
`


final, static and others >
Siva Nookala - 03 Mar 2017
A design pattern is some thing which a common solution for a common problem. In programming, although there are different domains or fields like banking, communications, travel etc., there are usually problems or situations which are common across all these domains. Some of these most common problems are identified as patterns and one such simple pattern is Singleton design pattern.

Singleton design pattern, as the name suggests is a problem in which we want only one object to be created. And the same object should be used across the application. This can be achieved by making the only constructor of the class as private and using the static method to create that only object and return it no matter how many times it is called.
class Singleton
{
    private static Singleton onlyObject;
    
    public static Singleton getInstance()
    {
        if(onlyObject == null)
        {
            onlyObject = new Singleton();
        }
        return onlyObject;
    }

    private Singleton()
    {
    }

    public void doSomeAction()
    {
    }
}

class A
{
    void method1()
    {
        Singleton s = Singleton.getInstance();
        s.doSomeAction();
    }
}

class B
{
    void method2()
    {
        Singleton.getInstance().doSomeAction();
    }
}
Here we have called the Singleton.getInstance() method in both class A and B. We do not know which method - method1() or method2() is called first. Irrespective of which method gets called, only one object is created and it is shared between these two methods. The same object will be used, no matter how many times method1 or method2 gets executed.
Please note that we have only discussed the simplest from of Singleton and there are other complexities which are not included here.

Dependent Topics : Static Keyword In Java  Using private Keyword In Java For Access Control   Access Modifiers In Java 

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.