1.饿汉模式
缺点:当加载该类时,静态方法也会被加载并生成一个对象占用内容,而这个对象不一定会使用,造成资源浪费;另外new SinletionTest()也无法获取构造函数异常;
public class SingletonTest {
private SingletonTest(){}
private static final SingletonTest instance = new SingletonTest();
public SingletonTest getInstance()
return instance;
}
}
2.饱汉模式
解决了饿汉模式的缺点,但是当多线程时会引起冲突,比如第一个线程要获取对象时,if(instance ==null) 后,同时第二个线程进入判断并获取对象,而第一个线程继续执行会获取第二个对象,造成冲突
public class SingletonTest {
private SingletonTest(){}
private static SingletonTest instance = null;
public SingletonTest getInstance(){
if(instance == null) {
instance = new SingletonTest();
}
return instance;
}
}
3.解决上述问题只需要给函数添加一个锁就可以了,但是造成性能低下,因为成了多线程了;
public class SingletonTest {
private SingletonTest(){}
private static SingletonTest instance =null;
public synchronized SingletonTest getInstance(){
if(instance == null) {
instance = new SingletonTest();
}
return instance;
}
}
- 根据枚举设计单例模式(jdk1.6之后)
public enum SingleEnum {
instance;
public static void getInstance(){
System.out.println("get123");
}
}
//测试
public class TestEnum{
public static void main(String args[]) {
for(int i=0; i<10; i++){
SingleEnum.instance.getInstance();
}
}
}
//打印结果
get123
get123
get123
get123
get123
get123
get123
get123
get123
get123