定义:确保一个类最多只有一个实例,并提供一个全局访问点,通俗的说,就是在整个运行过程中,该类最多只有一个实例化的对象。
节省内存和计算消耗、保证计算结果的正确性、方便管理
1.没有状态的工具类:例如日志工具类,通常只是记录我们日志信息的,不需要其他什么功能
2.全局信息类:例如统计网站的访问次数
优点:写法简单,该类该装载的时候就已经完成了实例化,这样就不会出现线程安全问题。
1 package designpattern.singletonmode; 2 /** 3 * 单例模式 4 * 静态常量模式 (可用) 5 * @author 6 * 7 */ 8 public class Singleton1 { 9 private final static Singleton1 INSTANCE = new Singleton1(); 10 11 private Singleton1() {} 12 13 public static Singleton1 getInstance() { 14 return INSTANCE ; 15 } 16 }
和上述 写法类似
1 package designpattern.singletonmode; 2 /** 3 * 单例模式 4 * 静态代码块 (可用) 5 * @author 6 * 7 */ 8 public class Singleton2 { 9 private final static Singleton2 INSTANCE ; 10 11 static { 12 INSTANCE = new Singleton2(); 13 } 14 15 private Singleton2() {} 16 17 public static Singleton2 getInstance() { 18 return INSTANCE ; 19 } 20 }
第三种写法:
预加载模式:主要为了优化,当我们需要的时候,再实例化,加载进来
但是这种往往存在线程不安全的问题
1 package designpattern.singletonmode; 2 /** 3 * 单例模式 4 * 懒加载 (不可用) 线程不安全 5 * @author 6 * 7 */ 8 public class Singleton3 { 9 private static Singleton3 instance ; 10 11 private Singleton3() { 12 13 } 14 15 public static Singleton3 getInstance() { 16 if(instance == null) { 17 instance = new Singleton3(); 18 } 19 return instance ; 20 } 21 }
第四种写法:
缺点:效率低,虽然线程安全
1 package designpattern.singletonmode; 2 /** 3 * 单例模式 4 * 懒加载 (可用) 线程安全 5 * @author 6 * 7 */ 8 public class Singleton4 { 9 private static Singleton4 instance ; 10 11 private Singleton4() { 12 13 } 14 15 public synchronized static Singleton4 getInstance() { 16 if(instance == null) { 17 instance = new Singleton4(); 18 } 19 return instance ; 20 } 21 }
第五中写法:
双重检查:为了检查,当两个线程进入第一个实例化判断中
volatile关键字:创建对象的时候是分3个步骤,该步骤会导致重排序,所以加了这个关键字防止重排序
1 package designpattern.singletonmode; 2 /** 3 * 单例模式 4 * 懒加载 (可用) 线程安全 5 * @author 6 * 7 */ 8 public class Singleton5 { 9 private volatile static Singleton5 instance ; 10 11 private Singleton5() { 12 13 } 14 15 public static Singleton5 getInstance() { 16 if(instance == null) { 17 synchronized (Singleton5.class) { 18 if(instance == null) { 19 instance = new Singleton5(); 20 } 21 } 22 23 } 24 return instance ; 25 } 26 }
原文:https://www.cnblogs.com/dujun-2021/p/14608707.html