Singleton pattern interview

前端 未结 8 2176
忘了有多久
忘了有多久 2021-02-04 14:26

I am recently asked about java related question in an interview with following code, since I am very new to java and barely code in Java so I really have no idea what the follow

8条回答
  •  迷失自我
    2021-02-04 14:35

    We use Singleton Pattern when we want to have only one object of this class and it will be used every where. So to restrict the class to create many objects, we should use private for constructor of this class. And create one public function to return the object of this class.

    public class MethodWin {
        private int isLoggedOn=0;
        private static MethodWin objectMethodWin = new MethodWin();
        private MethodWin() { }
        public static MethodWin getInstance() {
            return objectMethodWin;
        }
        public void setIsLoggedOn(int value) {
           this.isLoggedOn=value;
        }
        public int getIsLoggedOn() {
           return this.isLoggedOn;
        }
    }
    

    So when we need to create this obect, we should:

    MethodWin meth = MethodWin.getInstance();
    

提交回复
热议问题