呼市网站设计,wordpress月份归档要收录吗,2021没封的网站有人分享吗,网站建设所需要的材料文章目录 1.单例模式的作用2.单例模式的适用场景3.饿汉式静态常量#xff08;可用#xff09;静态代码块#xff08;可用#xff09; 4.懒汉式线程不安全#xff08;不可用#xff09;同步方法#xff08;线程安全#xff0c;但不推荐用#xff09;同步代码块#xf… 文章目录 1.单例模式的作用2.单例模式的适用场景3.饿汉式静态常量可用静态代码块可用 4.懒汉式线程不安全不可用同步方法线程安全但不推荐用同步代码块线程不安全不可用双重检查 volatile推荐用静态内部类推荐用枚举推荐用 1.单例模式的作用
为什么需要单例
节省内存和计算保证结果正确方便管理
2.单例模式的适用场景
无状态的工具类比如日志工具类不管是在哪里使用我们需要的只是它帮我们记录日志信息除此之外并不需要在它的实例对象上存储任何状态这时候我们就只需要一个实例对象即可。全局信息类比如我们在一个类上记录网站的访问次数我们不希望有的访问被记录在对象 A 上有的却记录在对象 B 上这时候我们就让这个类成为单例。
3.饿汉式
静态常量可用
/*** 饿汉式静态常量可用*/
public class Singleton1 {// 由于加了static关键字根据JVM的规定在类加载的时候就会完成INSTANCE的实例化这样就避免了线程同步问题private final static Singleton1 INSTANCE new Singleton1();// 构造函数是私有的private Singleton1() {}public static Singleton1 getInstance() {return INSTANCE;}
}静态代码块可用
/*** 饿汉式静态代码块可用*/
public class Singleton2 {private final static Singleton2 INSTANCE;// 与上一种写法类似由JVM保证了线程安全static {INSTANCE new Singleton2();}// 构造函数是私有的private Singleton2() {}public static Singleton2 getInstance() {return INSTANCE;}
}4.懒汉式
线程不安全不可用
/*** 懒汉式线程不安全不可用*/
public class Singleton3 {private static Singleton3 instance;// 构造函数是私有的private Singleton3() {}public static Singleton3 getInstance() {// 这种写法是线程不安全的不可用if (instance null) {instance new Singleton3();}return instance;}
}同步方法线程安全但不推荐用
/*** 懒汉式线程安全不推荐用*/
public class Singleton4 {private static Singleton4 instance;// 构造函数是私有的private Singleton4() {}// 这种写法虽然是线程安全的但是效率太低不推荐用public synchronized static Singleton4 getInstance() {if (instance null) {instance new Singleton4();}return instance;}
}同步代码块线程不安全不可用
/*** 懒汉式线程不安全不可用*/
public class Singleton5 {private static Singleton5 instance;// 构造函数是私有的private Singleton5() {}public static Singleton5 getInstance() {// 这种写法并不是线程安全的不可用if (instance null) {synchronized (Singleton5.class) {instance new Singleton5();}}return instance;}
}双重检查 volatile推荐用
优点线程安全延迟加载效率较高。
/*** 双重检查 volatile推荐用*/
public class Singleton6 {// volatile防止重排序private volatile static Singleton6 instance;// 构造函数是私有的private Singleton6() {}public static Singleton6 getInstance() {// 双重检查保证线程安全if (instance null) {synchronized (Singleton6.class) {if (instance null) {instance new Singleton6();}}}return instance;}
}为什么要用 volatile
新建对象 rs new Resource() 实际上有 3 个步骤
construct empty resource()call constructorassign to rs
如下图所示重排序会带来NPE问题NullPointerException, 空指针异常而使用 volatile 可以防止重排序。 静态内部类推荐用
/*** 静态内部类线程安全懒加载推荐用*/
public class Singleton7 {// 构造函数是私有的private Singleton7() {}// 由JVM的规定可知这种写法同时满足了线程安全和懒加载两个优点private static class SingletonInstance {private static final Singleton7 INSTANCE new Singleton7();}public static Singleton7 getInstance() {return SingletonInstance.INSTANCE;}
}枚举推荐用
单例模式的书写
/*** 枚举线程安全懒加载推荐用*/
public enum Singleton8 {INSTANCE;public void whatever() {}
}单例的使用
Singleton8.INSTANCE.whatever();哪种单例的实现方案最好
Joshua Bloch 大神在《Effective Java》中明确表达过的观点使用枚举实现单例的方法虽然还没有广泛采用但是单元素的枚举类型已经成为实现 Singleton 的最佳方法。
写法简单线程安全有保障懒加载避免反序列化破坏单例