单例模式 随笔

来源:互联网 发布:远程教学软件zoom 编辑:程序博客网 时间:2024/06/05 09:16
class Single{
        
        private static Single s =null;
        private Single() { }
        
        public static Single getInstance(){
                if(s == null)
                        s = new Single();
                return s;
        }
        
}
public class SingleDemo {


        public static void main(String[] agrs){
                
                Single s = null;
                s = s.getInstance();;
                
                System.out.println(s);
        }

}

1.构造方法私有化,对象由本类创建

2.懒汉模式下:用static修饰对象 private static Single s =null;(static修饰对象,对象一经创建就会一直保存在内存中,直到程序停止),所以确保了这个对象的唯一性。

3.静态方法只能访问静态变量

4.Single s=Single.getInstance()返回一个对象的引用,这个引用指向唯一的对象


参考:

http://bbs.itheima.com/thread-272812-1-1.html


https://zhidao.baidu.com/question/499665718.html