REMEMBER JAVA

MINTE9
2REMEMBER




Last update:   23-07-2021

Singleton Pattern

Singleton pattern restricts the instantiation of a class to a single instance. A private constructor hides the class for outside.
 CodeCopy
class LearningApp {

    public static void main(String[] args) {

        MyClass A = MyClass.getInstance();
        MyClass B = MyClass.getInstance();

        MyClass C = new MyClass(); 
            // Error: The constructor MyClass() is not visible
    }
}

class MyClass {

    private static final MyClass INSTANCE = new MyClass();

    private MyClass() {} // private constructor

    public static MyClass getInstance() {
        return INSTANCE;
    }
}
... 15 lines
˄˄˄
Static keyword is used for unique initialization. A static class is not automatically a Singleton class.
 CodeCopy
class LearningApp {

    public static void main(String[] args) {

        Obj o1 = new Obj();
        System.out.println( o1.getInstances() );// count = 1

        Obj o2 = new Obj();    
        System.out.println( o2.getInstances() );// count = 1
       
    }

    private static class Obj {

        private int count = 0; // it should be declared static

        private Obj() {
            count++; // without static it is always 1
        }

        public int getInstances() {
            return count;
        }
    }
}
... 17 lines
˄˄˄

Questions    
No. 29   Observer
CARD
28
63

        A B C D E F
🔔
1/5