懒汉模式
public class Demo{
public static Demo demo;
private Demo(){
}
public static Demo getInstace(){
if(demo==null){
demo=new Demo();
}
return Demo;
}
}
饿汉模式
public class Demo{
private static Demo instance=new Demo();
private Demo(){
}
public static Demo getInstance(){
return instance;
}
}
静态内部类单例模式
public class Demo{
private Demo(){
}
private static class inner{
private static final Demo instance=new Demo();
}
public static Demo getInstance(){
return inner.instance;
}
}
线程安全单例模式(双重锁单例模式)
public class Demo{
private volatile static Demo demo;
private Demo(){
}
public static Demo getDemo(){
if(demo==null){
synchronized(Demo.class){
if(demo==null){
demo=new Demo();
}
}
}
return demo;
}
}