设计模式之单例模式
来源:互联网 发布:mac卸载第三方软件 编辑:程序博客网 时间:2024/06/05 02:24
java设计模式之单例模式
一、单例模式的介绍
Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点
二、单例模式的实现
实现的方式有如下四种:
- /**
- *
- * 单例模式的实现:饿汉式,线程安全 但效率比较低
- */
- public class SingletonTest {
- private SingletonTest() {
- }
- private static final SingletonTest instance = new SingletonTest();
- public static SingletonTest getInstancei() {
- return instance;
- }
- }
/** * * 单例模式的实现:饿汉式,线程安全 但效率比较低 */public class SingletonTest {private SingletonTest() {}private static final SingletonTest instance = new SingletonTest();public static SingletonTest getInstancei() {return instance;}}
- /**
- * 单例模式的实现:饱汉式,非线程安全
- *
- */
- public class SingletonTest {
- private SingletonTest() {
- }
- private static SingletonTest instance;
- public static SingletonTest getInstance() {
- if (instance == null)
- instance = new SingletonTest();
- return instance;
- }
- }
/** * 单例模式的实现:饱汉式,非线程安全 * */public class SingletonTest {private SingletonTest() {}private static SingletonTest instance;public static SingletonTest getInstance() {if (instance == null)instance = new SingletonTest();return instance;}}
- /**
- * 线程安全,但是效率非常低
- * @author vanceinfo
- *
- */
- public class SingletonTest {
- private SingletonTest() {
- }
- private static SingletonTest instance;
- public static synchronized SingletonTest getInstance() {
- if (instance == null)
- instance = new SingletonTest();
- return instance;
- }
- }
/** * 线程安全,但是效率非常低 * @author vanceinfo * */public class SingletonTest {private SingletonTest() {}private static SingletonTest instance;public static synchronized SingletonTest getInstance() {if (instance == null)instance = new SingletonTest();return instance;}}
- /**
- * 线程安全 并且效率高
- *
- */
- public class SingletonTest {
- private static SingletonTest instance;
- private SingletonTest() {
- }
- public static SingletonTest getIstance() {
- if (instance == null) {
- synchronized (SingletonTest.class) {
- if (instance == null) {
- instance = new SingletonTest();
- }
- }
- }
- return instance;
- }
- }
/** * 线程安全 并且效率高 * */public class SingletonTest {private static SingletonTest instance;private SingletonTest() {}public static SingletonTest getIstance() {if (instance == null) {synchronized (SingletonTest.class) {if (instance == null) {instance = new SingletonTest();}}}return instance;}}
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- java 数据库连接池原理
- 我的java笔记
- java排序
- 企业IT不成功的五个原因(转)
- html删除a标签并且替换网址
- 设计模式之单例模式
- Android如何防止apk程序被反编译
- java 随机数
- Spring quartz 后台任务
- 行业网站防止注册机办法分析
- java中浮点数的精度
- 进制转换
- 全文搜索-Lucene
- Dom对XML的增删改查