单例模式--各种实现方式详解
2016-10-18 21:28
549 查看
1、饿汉模式
饿汉模式简单直接,但是有一点不好就是在初始化的时候太早了,没有做到什么时候用什么时候创建。
2、懒汉模式
懒汉模式这种实现是非线程安全的。单线程运行还可以。多线程就问题很大了。
3、Synchronized-懒汉模式
锁的粒度很大,java反射同样可以生成多个实例。
4、DCL-双检锁懒汉模式–避免反射的漏洞
5、使用Enum来实现单例
6、内部类实现单例模式
最后这个到底是不是能够防止反射,我个人认为是可以的,因为在反射中没有考虑到内部类的情况,只考虑了方法和字段。
//饿汉模式 public class singleton1 { private static singleton1 singleton = new singleton1(); /* * private static singleton1 singleton; * static{ * singleton = new singleton1(); * } */ private singleton1(){ } public static singleton1 getInstance(){ return singleton; } }
饿汉模式简单直接,但是有一点不好就是在初始化的时候太早了,没有做到什么时候用什么时候创建。
2、懒汉模式
//懒汉模式 public class singleton2 { private static volatile singleton2 singleton = null; private singleton2(){ } public static singleton2 getInstance(){ if(singleton == null) singleton = new singleton2(); return singleton; } }
懒汉模式这种实现是非线程安全的。单线程运行还可以。多线程就问题很大了。
3、Synchronized-懒汉模式
//加锁解决懒汉模式多线程不安全的问题 //synchronized 粒度有点大,加在方法上是串行的。 public class singleton3 { private static volatile singleton3 singleton = null; private singleton3(){ } public synchronized static singleton3 getInstance(){ if(singleton == null) singleton = new singleton3(); return singleton; } }
锁的粒度很大,java反射同样可以生成多个实例。
4、DCL-双检锁懒汉模式–避免反射的漏洞
//DCL双检锁机制实现懒汉模式的线程安全 public class singleton4 { private static volatile singleton4 singleton = null; private singleton4(){ } public static singleton4 getInstance(){ if(singleton == null) synchronized(singleton4.class){ if(singleton == null) singleton = new singleton4(); } return singleton; } }
5、使用Enum来实现单例
//枚举类型实现单例模式 public class singleton5 { private enum singletontest{ getsingleton; private static singletontest singleton; private singletontest(){ } public Connection getInstance(){ if (singleton == null){ // singleton =传进一个比如connection的实例 } return null; } } public static Connection getinstance(){ return singletontest.getsingleton.getInstance(); } }
6、内部类实现单例模式
public class singleton6 { private static class singleton1{ private static singleton6 singleton = new singleton6(); } private singleton6(){ } public static singleton6 getInstance(){ return singleton6.singleton1.singleton; } }
最后这个到底是不是能够防止反射,我个人认为是可以的,因为在反射中没有考虑到内部类的情况,只考虑了方法和字段。
相关文章推荐
- JAVA中的饿汉式和饱汉式单例模式及jdk中Runtime类的单例模式实现方式详解
- 基于Python中单例模式的几种实现方式及优化详解
- Spring4.3+Webscket 实现聊天、消息推送详解原创之各种实现方式(一)
- JS的平凡之路--单例模式的各种实现方式
- Singleton模式的各种实现方式。
- Rhyme/设计模式之单例模式详解—作用、应用场景、优点、五种单例模式实现方式
- 单利模式及python实现方式详解
- 混合式开发框架模式中各种登陆方式的配置实现
- 【Todo】单例模式各种实现方式及并发安全
- pig的各种运行模式与运行方式详解
- VMware网络配置详解:三种网络模式简介及实现
- 1.singleton模式的的两种实现方式
- 各种字符编码方式详解及由来(ANSI,UNICODE,UTF-8,GB2312,GBK)
- 各种字符编码方式详解及由来(ANSI,UNICODE,UTF-8,GB2312,GBK)
- 双机热备的实现模式 - 基于共享存储与纯软件方式
- 用递归的方式实现各种进制间的转换
- 【工作流】PE中的资源模式的实现方式
- 关于单例(Singleton)模式实现方式的反思
- 史上最强jquery1.3.2轻松打造div模式层! asp.net和html和MagicAjax实现3种方式! 已更新!
- [设计模式]DAO的实现方式探讨_Part II