欢迎关注微信公众号:FSA全栈行动 👋java
经过单例模式能够保证系统中,应用该模式的类只有一个对象实例。安全
好处:微信
分类:markdown
class
一加载就建立)getInstance()
时再建立)实现步骤:多线程
/** * 单式模式:饿汉式 * * @author GitLqr */
public class SingletonHungry {
private static SingletonHungry instance = new SingletonHungry();
private SingletonHungry() {
}
public static SingletonHungry getInstanceHungry() {
return instance;
}
}
复制代码
DCL,即双重检查锁定 (Double-Checked-Locking)函数
synchronized
前第一次判空:避免没必要要的加锁同步,提升性能synchronized
后第二次判空:避免出现多线程安全问题volatile
修饰 instance:避免指令重排序问题/** * 单例模式:懒汉式 (DCL + volatile) * * @author GitLqr */
public class SingletonLazy {
private static volatile SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
复制代码
Holder
静态内部类:外部类加载时,并不会直接致使静态内部类被加载,在调用 getInstance()
时才会触发该静态内部类被加载,因此,能够延时执行。Holder.instance
static 字段:同一个加载器下,一个类型只会初始化一次,故自然的线程安全。/** * 单例模式:懒汉式 (静态内部类) * * @author GitLqr */
public class SingletonLazyClass {
private static class Holder {
private static SingletonLazyClass instance = new SingletonLazyClass();
}
public static SingletonLazyClass getInstance() {
return Holder.instance;
}
private SingletonLazyClass() {
}
}
复制代码
注意:
静态内部类
相比DCL
代码简洁不少,即有饿汉式的优点,又能够作到延时初始化,看似很完美,但其有一个致命问题,即没法传参,因此,实际开发中,要根据实际状况来选择其中一种实现方式。oop
/** * 单例模式:懒汉式 (枚举) * * @author GitLqr */
public enum SingletonEnum {
INSTANCE;
// 枚举与普通类同样,能够拥有字段和方法
public void method() {
// TODO
}
}
复制代码
注意:缺点跟
静态内部类
方式同样,外部没法传参。性能
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
复制代码
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {
}
public static synchronized SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
复制代码
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
复制代码
public class SingletonLazy {
private static volatile SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
复制代码
若是文章对您有所帮助, 请不吝点击关注一下个人微信公众号:FSA全栈行动, 这将是对我最大的激励. 公众号不只有Android技术, 还有iOS, Python等文章, 可能有你想要了解的技能知识点哦~spa