自在如风

Java 单例设计模式

  • 解决一个类在内存只存在一个对象的问题

饿汉式

//Single类一进内存,就已经创建好了对象。
class Single
{
    private static Single s = new Single();
    private Single(){}
    public static Single getInstance(){
	return s;
    }
}

懒汉式

//Single类进内存,对象还没有存在,只有调用了getInstance方法时,才建立对象。
class Single
{
    private static Single s = null;
    private Single(){}
    public static Single getInstance(){
	if(s==null)
	{
	    synchronized(Single.class){				
		if(s==null){
		    s = new Single();
		}
	    }
	return s;
	}
    }
}
posted @ 2020-03-30 19:25  我是痕  阅读(94)  评论(0编辑  收藏  举报