How to make sure that there is just one instance of class in JVM?

后端 未结 9 1546
离开以前
离开以前 2021-02-01 05:48

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a s

9条回答
  •  庸人自扰
    2021-02-01 06:23

    For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.

    E.g: If I want only one object for this Connect class:

    public final class Connect {
    
        private Connect() {}
    
        private volatile static Connect connect = null;
    
        public static Connect getinstance() {
            if(connect == null) {
                synchronized (Connect.class) {
                    connect = new Connect();
                }
            }
            return connect;
        }
    }
    

    Here the constructor is private, so no one can use new keyword to make a new instance.

提交回复
热议问题