单例模式实现

简介: 1. 单线程可用 2. 使用final常量 3. 加锁构造 4. 方法级加锁 5. 静态内部类实现,多线程可用 6. 拒绝强行反射创建我

1. 单线程可用

public class Singleton {

    private static Singleton singleton;

    private Singleton() {
    }

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

2. 使用final常量

public class Singleton {

    private static final Singleton singleton = new Singleton();

    private Singleton() {
    }

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

3. 加锁构造

public class Singleton {

    private static Singleton singleton;

    private static final Lock LOCK = new ReentrantLock();

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (null == singleton) {
            LOCK.lock();
            if (null == singleton) {
                singleton = new Singleton();
            }
            LOCK.unlock();
        }
        return singleton;
    }
}

4. 方法级加锁

public class Singleton {

    private static Singleton singleton;

    private Singleton() {
    }

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

    private static synchronized void init(){
        if(null == singleton){
            singleton = new Singleton();
        }
    }
}

5. 静态内部类实现,多线程可用

public class Singleton {

    private Singleton() {
    }

    public static Singleton getInstance() {
        return Container.singleton;
    }

    private static class Container {
        private static Singleton singleton = new Singleton();
    }
}

6. 拒绝强行反射创建我

public class Singleton {

    private Singleton() {
        if (null != Container.singleton) {
            throw new UnsupportedOperationException(); // 报错啦
        }
    }

    public static Singleton getInstance() {
        return Container.singleton;
    }

    private static class Container {
        private static Singleton singleton = new Singleton();
    }
}
目录
相关文章
|
5月前
|
设计模式 安全
详细讲解什么是单例模式
详细讲解什么是单例模式
|
4月前
|
设计模式 安全 Java
单例模式分享
单例模式分享
16 0
|
设计模式 安全 编译器
2023-6-12-第三式单例模式
2023-6-12-第三式单例模式
70 0
|
5月前
|
设计模式 安全
【单例模式】—— 每天一点小知识
【单例模式】—— 每天一点小知识
|
设计模式 Java Spring
什么场景要使用单例模式,什么场景不能使用?
经常有小伙伴问我,设计模式学了这么久,每次看到概念也都能理解。但是,就是不知道怎么用,在哪里能用?我告诉大家,设计模式,不是为了要用而用的,而是作为前人总结下来的经验,等到哪天需要用的时候,你能想起来为你所用。
94 0
|
安全 Java
原来要这么实现单例模式
原来要这么实现单例模式
50 0
|
设计模式 前端开发
关于单例模式我所知道的
关于单例模式我所知道的
57 0
关于单例模式我所知道的
|
设计模式 安全 Java
回顾一下单例模式
回顾一下单例模式
|
数据采集 设计模式 算法
大佬,人人都说精通的单例模式,你精通了吗
大佬,人人都说精通的单例模式,你精通了吗
81 0
大佬,人人都说精通的单例模式,你精通了吗
|
开发框架 安全 Java
单例模式的应用(1)
单例模式的应用(1)
140 0