单例模式

设计为私有构造方法,不允许对象被 new 出来
这是一种创建型模式,主要用来创建只需要创建一次的对象,比如数据库连接,线程池创建等。

分类

按加载顺序分 “懒汉” 与 “饿汉” 式
按线程安全也可分为线程安全与非线程安全

package com.carl.singleton;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class ThreadPoolDirectLoad {

    private static ExecutorService threadPool = Executors.newFixedThreadPool(5);

    private ThreadPoolDirectLoad() {
    }

    public static ExecutorService getThreadPool() {
        return threadPool;
    }
}

package com.carl.singleton;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class ThreadPoolLazyLoad {

    private ThreadPoolLazyLoad() {
    }

    public static ExecutorService getThreadPool() {
        return Help.threadPool;
    }

    private static class Help {
        private static ExecutorService threadPool = Executors.newFixedThreadPool(5);
    }
}

package com.carl.singleton;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class ThreadPoolFactory {

    private enum ThreadPoolEnum {

        INSTANCE;

        private ExecutorService threadPool;

        private ThreadPoolEnum() {
            threadPool = Executors.newFixedThreadPool(5);
        }

        public ExecutorService getInstance() {
            return threadPool;
        }

    }

    public static ExecutorService getInstance() {
        return ThreadPoolEnum.INSTANCE.getInstance();
    }

}

其他

另外还有通过锁实现的懒汉与饿汉式,相对复杂些,工作中很少使用,
同样是达到线程安全的目的,我更喜欢枚举实现


↙↙↙阅读原文可查看相关链接,并与作者交流