How to create a singleton class

前端 未结 7 1060
粉色の甜心
粉色の甜心 2020-12-02 13:10

What is the best/correct way to create a singleton class in java?

One of the implementation I found is using a private constructor and a getInstance() method.

<
7条回答
  •  温柔的废话
    2020-12-02 13:55

    just follow the singleton pattern class diagram,

    SingletonClass - singletonObject: SingletonClass - SingletonClass() + getObject(): SingletonClass

    Key point,

    • private your constructor
    • the instance of your class should be inside the class
    • provide the function to return your instance

    Some code,

    public class SingletonClass {
        private static boolean hasObject = false;
        private static SingletonClass singletonObject = null;
    
        public static SingletonClass getObject() {
            if (hasObject) {
                return singletonObject;
            } else {
                hasObject = true;
                singletonObject = new SingletonClass();
                return singletonObject;
            }
        }
    
        private SingletonClass() {
            // Initialize your object.
        }
    }
    

提交回复
热议问题