史上最简单的单例模式详解

来源:互联网 发布:淘宝店铺什么是c店 编辑:程序博客网 时间:2024/05/21 04:21

单例模式:只给外界提供一次资源,优点两个。 1. 效率高 2. 有安全保障


单例模式有两种分别为懒汉式和饿汉式


懒汉式

public class LazyMethod {


private LazyMethod() {}

static LazyMethod result;
public static LazyMethod getInstance(){
if(null == result){
result = new LazyMethod();
}
return result;
}
}


很显然在多并发的情况下 是线程不安全的, 当然可以使其线程安全 比如加Synchronized关键字 Lock关键字等等。


推荐饿汉式





public class HungryMethod {


private static HungryMethod result = new HungryMethod();
private HungryMethod() {}

public static HungryMethod getInstance(){
return result;
}
}



很显然是线程安全的。


1 0