单例模式------确保一个类只有一个实例,并提供一个全局访问点。
类图:
1、懒汉式
/**
* 懒汉式
* @author 码农
*
*/
public class LazySingleton {
private static LazySingleton uniqueInstance;
private LazySingleton(){}
public static LazySingleton getInstance(){
if(uniqueInstance==null){
uniqueInstance=new LazySingleton();
}
return uniqueInstance;
}
}
2、饿汉式
/**
* 饿汉式
* @author 码农
*
*/
public class HungrySingleton {
private static HungrySingleton uniqueInstance=new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance(){
return uniqueInstance;
}
}
3、线程安全模式
/**
* 线程安全模式
* @author 码农
*
*/
public class SynchronizedSingleton {
private static SynchronizedSingleton uniqueInstance;
private SynchronizedSingleton(){}
public static synchronized SynchronizedSingleton getInstance(){
if(uniqueInstance==null){
uniqueInstance=new SynchronizedSingleton();
}
return uniqueInstance;
}
}
4、双重枷锁模式
/**
* 双重加锁模式
* @author zyzhmily
*
*/
public class DoubleLockSingleton {
private volatile static DoubleLockSingleton uniqueInstance;
private DoubleLockSingleton(){}
public static DoubleLockSingleton getInstance(){
if(uniqueInstance==null){
synchronized(DoubleLockSingleton.class){
if(uniqueInstance==null){
uniqueInstance=new DoubleLockSingleton();
}
}
}
return uniqueInstance;
}
}