博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单例模式
阅读量:2384 次
发布时间:2019-05-10

本文共 1917 字,大约阅读时间需要 6 分钟。

1.懒汉-线程不安全

1 public class Singleton {   2     private static Singleton instance;   3     private Singleton (){}   4    5     public static Singleton getInstance() {   6     if (instance == null) {   7         instance = new Singleton();   8     }   9     return instance;  10     }  11 }

2.懒汉-线程安全(效率很低,99%情况下不需要同步。)

1 public class Singleton {   2     private static Singleton instance;   3     private Singleton (){}   4     public static synchronized Singleton getInstance() {   5     if (instance == null) {   6         instance = new Singleton();   7     }   8     return instance;   9     }  10 }

3.饿汉

1 public class Singleton {  2     private static Singleton instance = new Singleton();  3     private Singleton (){}  4     public static Singleton getInstance() {  5     return instance;  6     }  7 }

4.饿汉2

1 public class Singleton {   2     private Singleton instance = null;   3     static {   4     instance = new Singleton();   5     }   6     private Singleton (){}   7     public static Singleton getInstance() {   8     return this.instance;   9     }  10 }

5.静态内部类

1 public class Singleton {  2     private static class SingletonHolder {  3     private static final Singleton INSTANCE = new Singleton();  4     }  5     private Singleton (){}  6     public static final Singleton getInstance() {  7     return SingletonHolder.INSTANCE;  8     }  9 }

6.枚举

1 public enum Singleton {  2     INSTANCE;  3     public void whateverMethod() {  4     }  5 }

7.双重校验锁

1 public class Singleton {   2     private volatile static Singleton singleton;   3     private Singleton (){}   4     public static Singleton getSingleton() {   5     if (singleton == null) {   6         synchronized (Singleton.class) {   7         if (singleton == null) {   8             singleton = new Singleton();   9         }  10         }  11     }  12     return singleton;  13     }  14 }

 

posted @
2017-05-31 09:04 阅读(
...) 评论(
...)

转载地址:http://nhcab.baihongyu.com/

你可能感兴趣的文章
openstack的swift组件详解
查看>>
两大主流开源分布式存储的对比:GlusterFS vs. Ceph
查看>>
面试笔试动态规划问题--python篇
查看>>
linux下的svn常用命令使用指南
查看>>
阿里云iot事业部一面面经
查看>>
《云计算架构技术与实践》
查看>>
《云计算架构技术与实践》序言(李德毅院士)
查看>>
《云计算架构技术与实践》连载(2):1.2 云计算的发展趋势
查看>>
《跨界杂谈》企业商业模式(七):其他
查看>>
STL介绍 - map
查看>>
ssh 命令的用法
查看>>
scp 命令的用法
查看>>
ldcofig 命令的用法
查看>>
tar 命令的用法
查看>>
mount 命令的用法
查看>>
fdisk 命令的用法
查看>>
ln 命令的用法
查看>>
ORACLE的归档空间满导致的监听故障数据库无法启动
查看>>
GRID卸载及重新安装
查看>>
shell 带参数脚本
查看>>