饿汉模式
public class Hungry{
private Hungry(){}
private static final Hungry instance = new Hungry();
public static Hungry getInstance(){
return instance;
}
}
public class Hungry{ private Hungry(){} private static final Hungry instance = new Hungry(); public static Hungry getInstance(){ return instance; } }
懒汉模式
会在需要的时候加载类对象(延时加载),节省存储资源,线程不安全
public class LazyOne{
private LazyOne(){
}
private static LazyOne instance = null;
public static LazyOne getInstance(){
if(instance==null){
instance = new LazyOne();
}
return instance;
}
}
存在性能问题
public class LazyTwo {
private LazyTwo() {}
private static LazyTwo instance = null;
//存在性能问题
public static synchronized LazyTwo getInstance() {
if(instance == null) {
instance = new LazyTwo();
}
return instance;
}
}
防止单例被破坏。
public class LazyThree{
//如果去掉static,就可以被反射强制访问,调用两次了
private static boolean initialized = false;
//防止反射注入
//默认使用LazyThree的时候,会先初始化内部类
//如果没使用的话,内部类是不加载的
private LazyThree(){
synchronized (LazyThree.class){
if(initialized=false){
initialized=!initialized;
}else {
throw new RuntimeException("单例已被侵犯");
}
}
}
public static LazyThree getInstance(){
return Lazyholder.Y;
}
//默认不加载
private static class Lazyholder{
private static final LazyThree Y=new LazyThree();
}
}
第一次if判断,如果不为空,就不需要去争抢锁,第二次if判断,是否需要创建实例对象。
可以被反射破坏单例。
public class LazyFour {
private volatile static LazyFour instance=null;
private LazyFour(){
}
public static LazyFour getInstance(){
if(instance==null){
synchronized (LazyFour.class){
if(instance==null){
instance=new LazyFour();
}
}
}
return instance;
}
}