美文网首页
02-创建型模式-单例模式

02-创建型模式-单例模式

作者: 菜出意料 | 来源:发表于2019-12-16 20:15 被阅读0次

单例模式

单例模式:类只能创建一个实例,并提供对实例的静态访问方法。
要点:

  • 私有构造器
  • 静态私有变量
  • 声明可全局访问的公有静态方法

饿汉式

饿汉式:静态私有变量默认初始化(线程安全)。

public class Singleton {
    private Singleton() {}
    private static Singleton singleton = new Singleton();
    public static Singleton getInstance() {
        return singleton;
    }
}

懒汉式(非线程安全)

懒汉式:静态私有变量默认不初始化(非线程安全)。

public class Singleton {
    private Singleton() {}
    private static Singleton singleton;
    public static Singleton getInstance() {
        if (singleton == null) singleton = new Singleton();
        return singleton;
    }
}

懒汉式-synchronized(线程安全)

线程安全,性能很差。

public class Singleton {
    private Singleton() {}
    private static Singleton singleton;
    public static synchronized Singleton getInstance() {
        if (singleton == null) singleton = new Singleton();
        return singleton;
    }
}
// 或
public class Singleton {
    private Singleton() {}
    private static Singleton singleton;
    public static Singleton getInstance() {
        synchronized (Singleton.class) {
            if (singleton == null) singleton = new Singleton();
        }
        return singleton;
    }
}

懒汉式-双重检测(double check)(线程安全)

线程安全,比synchronized性能好。

public class Singleton {
    private Singleton() {}
    private static Singleton singleton;
    public static Singleton getInstance() {
        // 第一次检测
        if (singleton == null) {
            synchronized (Singleton.class) {
                // 第二次检测
                if (singleton == null) singleton = new Singleton();
            }
        }
        return singleton;
    }
}

静态内部类(线程安全)

线程安全,性能很好。

public class Singleton {
    private Singleton() {}
    private static class SingletonHoler {
        private static Singleton singleton = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHoler.singleton;
    }
}

枚举(线程安全)

线程安全,性能很好。

public enum  Singleton {
    INSTANCE
}

相关文章

  • 单例模式

    单例 单例模式,是一种设计模式,属于创建型设计模式,还有一种创建型设计模式,工厂模式。设计模式总共有23种,三大类...

  • 开发之设计模式-单例模式

    设计模式 设计模式分为三大类:创建型、结构型、行为型在Java中有24中设计模式 创建型:单例 1、为什么用单例模...

  • 【设计模式】创建型设计模式汇总

    创建型设计模式汇总 1. 单例模式 1.1 单例模式的定义 一个类只允许创建一个对象或实例。 1.2 单例模式的作...

  • 23种设计模式学习总结

    创建型设计模式 主要解决对象的创建问题,封装复杂的创建过程,解耦对象的创建代码合使用代码。 单例模式 单例模式用来...

  • 2.架构设计(单例模式设计)

    1.设计模式分为三个类 创建型 结构型 行为型 2.创建型:单例模式 为什么用单例模式?如果你看到这个问题,你怎么...

  • Python 之单例模式

    简介:单例模式(Singleton Pattern) 是最简单的设计模式之一,属于创建型的设计模式。单例模式涉及到...

  • PHP常用设计模式

    # 创建型 单例模式 工厂模式 工厂抽象模式 原型模式 建造者模式 # 结构型 # 行为型 # 3.注册模式 # ...

  • 设计模式分类

    经典23种设计模式: 创建型设计模式: Singleton Pattern(单例模式) PrototypePatt...

  • PHP设计模式—创建型设计模式

    ** 创建型设计模式 **: 单例模式(Singleton Pattern) 工厂方法模式(Factor Patt...

  • S4. 单例模式

    单例模式(Singleton) 介绍 单例模式是创建型设计模式,即用于创建对象的设计。其能够保证当前系统仅存在一个...

网友评论

      本文标题:02-创建型模式-单例模式

      本文链接:https://www.haomeiwen.com/subject/beclnctx.html