Singleton Pattern

There may be a need to have one and only one instance of a given class during the lifetime of an application.

public class X {
    private static X instance;
    private X(){}    //private constructor
    public static X getInstance(){    //static method to get an instance without instantiating the class
        if (instance == null) instance = new X();
        return instance;
    }
    //other methods which may be synchronized
}

Another approach is to have a final class with all the methods as static. In this case, you can’t create any instance of the class and can call the static methods directly but this method is a bit weird!

page_revision: 1, last_edited: 1210757666|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License