Java单例模式的几种写法

Java单例模式几种写法

1、饿汉式(最常见写法,推荐写法)

  1. 第一种写法
public class Singleton1 {

    private static final Singleton1 INSTANCE = new Singleton1();

    // 构造器私有化,防止从外部new
    private Singleton1() {
    }

    /**
     * 外部只能通过调用该方法获取实例
     */
    public static Singleton1 getInstance() {
        return INSTANCE;
    }
}
  1. 第二种写法
public class Singleton1 {

    private static final Singleton1 INSTANCE;

    static {
        INSTANCE = new Singleton1();
    }
    
    // 构造器私有化,防止从外部new
    private Singleton1() {
    }

    /**
     * 外部只能通过调用该方法获取实例
     */
    public static Singleton1 getInstance() {
        return INSTANCE;
    }
}

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

  1. 在多线程下会导致new出来的不是同一个实例
public class Singleton2 {
    // 构造器私有化,防止从外部new
    private Singleton2() {
    }

    private static Singleton2 INSTANCE;

    public Singleton2 getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton2();
        }
        return INSTANCE;
    }
}
  1. 加锁方式(影响性能)
public class Singleton2 {
    // 构造器私有化,防止从外部new
    private Singleton2() {
    }

    private static Singleton2 INSTANCE;

    public synchronized Singleton2 getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton2();
        }
        return INSTANCE;
    }
}
  1. 通过减少同步代码块加锁(多线程下也会导致不是同一个实例)
ublic class Singleton2 {
    // 构造器私有化,防止从外部new
    private Singleton2() {
    }

    private static Singleton2 INSTANCE;

    public Singleton2 getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton2.class) {
                INSTANCE = new Singleton2();
            }
        }
        return INSTANCE;
    }
}
  1. 双重检查
public class Singleton2 {
    // 构造器私有化,防止从外部new
    private Singleton2() {
    }

    private static Singleton2 INSTANCE;

    public Singleton2 getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton2.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton2();
                }
            }
        }
        return INSTANCE;
    }
}

3. 内部类方式

  1. 通过定义一个内部类的方式调用,运用了类加载机制,保证线程安全
public class Singleton2 {
    // 构造器私有化,防止从外部new
    private Singleton2() {
    }

    public static class Singleton2Holder {
        private Singleton2Holder() {
        }
        private static final Singleton2 INSTANCE = new Singleton2();
    }

    public static Singleton2 getInstance() {
        return Singleton2Holder.INSTANCE;
    }
}

4. 枚举方式(推荐写法)

public enum Singleton {
    
    INSTANCE;

    public void test() {
        // do something
    }

    public static void main(String[] args) {
        Singleton.INSTANCE.test();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值