1、定义
单例模式:确保一个类只有一个实例,提供一个全局访问点
单例6种写法
1、饿汉式
/**
*
* 饿汉式单例
* @author chentong
* 非线程安全
*
*/
public class HungrySingleton {
private static HungrySingleton hungrySingleton = new HungrySingleton();
private HungrySingleton(){
}
public HungrySingleton getInstance(){
return hungrySingleton;
}
}
2、懒汉
/**
* 懒汉式单例
* 线程安全
* @author chentong
*/
public class LazySingleton {
private static LazySingleton lazySingleton;
private LazySingleton(){
}
public static synchronized LazySingleton getInstance(){
if(lazySingleton == null){
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
3、内部静态类
/**
* 内部静态类 单例
* @author chentong
*
*/
public class Singleton {
private Singleton(){
}
/**
* 静态内部类
*/
private static class SingletonHolder{
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
4、Double Check
public class DoubleCheckSingleton {
private static volatile DoubleCheckSingleton doubleCheckSingleton;
private DoubleCheckSingleton(){
}
public static DoubleCheckSingleton getInstance(){
if(doubleCheckSingleton == null){
synchronized (DoubleCheckSingleton.class){
if (doubleCheckSingleton == null){
doubleCheckSingleton = new DoubleCheckSingleton();
}
}
}
return doubleCheckSingleton;
}
}
5、枚举单例
/**
*
* 枚举法式单例
* @author chentong
* 枚举默认线程安全
* 防止反序列化重新创建新的对象
*
*/
public enum EnumSingleton {
INSTANCE;
public void doSomething(){
}
/**
* 使用示例
*/
public static class SingleDemo {
public static void main(String[] args) {
EnumSingleton singleton = EnumSingleton.INSTANCE;
singleton.doSomething();
}
}
}
6、容器单例
public class MapSingleton {
private static Map<String ,Object> objectMap = new HashMap<>( );
private MapSingleton(){
}
public static void registerService(String key,Object object){
if (!objectMap.containsKey( key )){
objectMap.put( key,object );
}
}
public static Object getService(String key){
return objectMap.get( key );
}
}