Java: getInstance vs Static

后端 未结 6 817
清歌不尽
清歌不尽 2021-01-30 11:17

What is the purpose of getInstance() in Java?

During my research I keep reading that getInstance() helps achieve a Singleton design pattern (w

6条回答
  •  醉梦人生
    2021-01-30 11:52

    Singleton

    A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;

    public class MySingleton {
    
        private int myNumber;
        private static MySingleton instance;
    
        public static MySingleton getInstance() {
            if (instance == null) {
                 instance = new MySingleton();
            }
            return instance;
        }
    
        private MySingleton() {}
    
        public void setMyNumber(int myNumber) {
            this.myNumber = myNumber;
        }
    
        public int getMyNumber() {
           return myNumber;
        }
    }
    

    Now we are going to set the value of this number in the A class:

    public class A {
        /*...*/
        MySingleton mySingleton = MySingleton.getInstance();
        mySingleton.setMyNumber(42);
        /*...*/
    }
    

    Then, you can access this value from another class:

    public class B {
        /*...*/
        MySingleton mySingleton = MySingleton.getInstance();
        int number = mySingleton.getMyNumber();
        /*...*/
    }
    

    In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:

    All the values stored in the singleton will be accessible from "everywhere".


    Static class

    The purpose is different, here the advantage is to use an object without having to create it.

    For example:

    public static class MyStaticClass {
        public static void sayHello() {
            System.out.println("Hello");
        }
    }
    

    Now you can use the sayHello() method from any classes by calling:

    MyStaticClass.sayHello(); 
    

提交回复
热议问题