java--单例模式
来源:互联网 发布:中国近几年gdp数据表格 编辑:程序博客网 时间:2024/06/11 01:17
单例模式
设计为私有构造方法,不允许对象被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(); }}
其他
另外还有通过锁实现的懒汉与饿汉式,相对复杂些,工作中很少使用,
同样是达到线程安全的目的,我更喜欢枚举实现
https://testerhome.com/topics/10042
阅读全文
0 0
- java单例模式
- Java单例模式
- java单例模式
- java单例模式
- Java单例模式
- Java单例模式
- java单例模式
- Java单例模式
- java 单例模式
- java单例模式
- java单例模式
- java单例模式
- java 单例模式
- JAVA单例模式
- java单例模式 .
- Java 单例模式
- Java单例模式
- Java 单例模式
- 如何创建Windows服务
- [Python]网络爬虫(六):一个简单的百度贴吧的小爬虫
- 百度ueditor的初步使用
- 使用AndroidStudio编译NDK的方法及错误解决方案
- [Python]网络爬虫(七):Python中的正则表达式教程
- java--单例模式
- goLang map 的简单应用
- <c语言>如何将数组初始化为0?
- 客户端向HDFS读写数据机制
- STM32系统定时器SysTick
- Unity3D-Unity中CacheServer(缓存服务器)的部署与使用
- Bringing up interface Auto_eth1: Error: No suitable device found: no device found for connection 'A
- Rust: codewars 的Count of positives / sum of negatives
- Java语言发展史