zoukankan      html  css  js  c++  java
  • 单例模式

    1、饿汉式 (静态常量)

    public class Singleton {

    private final static Singleton INSTANCE = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
    return INSTANCE;
    }
    }

    2、饿汉式(静态代码块)

    public class Singleton {

    private static Singleton instance;

    static {
    instance = new Singleton();
    }

    private Singleton() {}

    public static Singleton getInstance() {
    return instance;
    }
    }

    3、懒汉式(线程不安全)

    public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

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

    4、懒汉式(线程安全,同步方法)

    public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

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

    5、懒汉式(线程安全,同步代码块)

    public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

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

    6、双重检查[推荐用]

    public class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

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

    7、静态内部类[推荐用]

    public class Singleton {

    private Singleton() {}

    private static class SingletonInstance {
    private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
    return SingletonInstance.INSTANCE;
    }
    }

    8、枚举[推荐用]

    public enum Singleton {
        INSTANCE;
        public void whateverMethod() {
    
        }
    }
  • 相关阅读:
    finalShell 文件上传拖拽失败
    centos6.x 启动docker报错
    笔记本查看当前登录用户
    保存文件到D盘时显示“你没有权限在此文件夹中保存文件,请联系管理员“其他文件夹正常?
    关于MongoDB配置文件的一个小细节
    ubuntu: mongoDB安装,无需下载
    Java 连接虚拟机中MongoDB 所需依赖
    信息知识竞赛刷题助手
    python超多常用知识记录
    python字典键或值去重
  • 原文地址:https://www.cnblogs.com/yuyangcoder/p/10019944.html
Copyright © 2011-2022 走看看