单例模式:
懒汉式—线程不安全:
public class Singleton{
private static Singleton Instance;
private Singleton(){
}
public static Singleton GetInstance(){
if(Instance==null){
Instance=new Singleton();
}
return Instance;
}
}
优点:
私有静态类变量uniqueInstance被延迟实例化,这样做的好处是如果没有用到该类,那么就不会实例化uniqueInstance从而节约资源。
缺点:
线程不安全,多线程情况下会多次创建实例。
饿汉式—线程安全:
public class Singleton{
private static Singleton Instance=new Singleton();
private Singleton(){
}
public static Singleton GetInstance(){
return Instance;
}
}
优点:
采取直接实例化uniqueInstance的方式就不会产生线程不安全问题。
缺点:
直接实例化的方式也丢失了延迟实例化带来的节约资源的好处。
懒汉式—线程安全:
private static Singleton Instance;
public static synchronized Singleton getInstance(){
if(Instance==null){
Instance=new Singleton();
}
return Instance;
}
双重校验锁—线程安全:
public class Singleton{
private volatile static Singleton Instance;
private Singleton(){
}
public static Singleton getInstance(){
if(Instance==null){//先判断实例是否存在,不存在再加锁
synchronized(Singleton.class){//由于Instace实例有没有被创建过实例不知道,只能对其clss加锁
if(Instance==null){//当多个线程的时候,只有一个进入,避免多次创建对象!
Instance=new Singleton();
}
}
}
return Instance;
}
}