原博主地址:(https://blog.csdn.net/LoveLion/article/details/17517213)
单例模式,原本以为这是我唯一熟悉的设计模式,后来才发现,我之前做的单例都是线程不安全的。
懒汉模式占内存
饿汉模式第一次慢
IoDH模式双全
单例模式(Singleton Pattern):确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。单例模式是一种对象创建型模式。
//懒汉模式,就是很懒,不管你要不要
public class Sun {
private static Sun sun = new Sun();
private Sun() {
}
public static Sun getSun() {
return sun;
}
}
//饿汉模式
public class Sun {
private static Sun sun = null;
private Sun() {
}
public static Sun getSun() {
if(sun==null) {
synchronized (Sun.class) {
if(sun==null) {
sun = new Sun();
}
}
}
return sun;
}
}
//Initialization Demand Holder (IoDH)使用静态内部类
public class Sun {
private Sun() {
}
private static class Handler{
private static Sun sun = new Sun();
}
public static Sun getSun() {
return Handler.sun;
}
}