单例模式的特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。 -《Java与模式》
单例类可以是没有状态的,仅用做提供工具性函数的对象。既然是提供工具性函数,也就没有必要创建多个实例。
下面列举单例模式的几种实现:
- 单元素的枚举类型实现Singleton – the preferred approach.enum类型是Jdk1.5引入的一种新的数据类型.其背后的基本想法:通过公有的静态final域为每个枚举常量导出实例的类。因为没有可访问的构造器,枚举类型是真正的final。既不能创建枚举类型实例,也不能对它进行扩张 。枚举类型是实例受控的,是单例的泛型化,本质上是氮元素的枚举 -《Effective Java》P129
复制代码
1
2
3
4
5
6
7
8
9public enum Singleton{ INSTANCE; public void execute(){…} public static void main(String[] agrs){ Singleton sole=Singleton.INSTANCE; sole.execute(); } }
- 懒汉式 – Lazy initialization . 构造函数是private,只有通过Singleton才能实例化这个类。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Singleton{ private volatile static Singleton uniqueInstance=null; private Singleton(){} public static Singleton getInstance(){ if(uniqueInstance==null){ synchronized(Singleton.class){ if(uniqueInstance==null){ uniqueInstance=new Singleton(); } } } return uniqueInstance; } //other useful methods here }
- 饿汉式 – Eager initialization
复制代码
1
2
3
4
5
6
7public class Singleton{ private static Singleton uniqueInstance=new Singleton(); private Singleton(){} public static Singleton getInstance(){ return uniqueInstance; } }
- static block initialization
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Singleton{ private static final Singleton instance; static{ try{ instance=new Singleton(); }catch(IOException e){ thronw new RuntimeException("an error's occurred!"); } } public static Singleton getInstance(){ return instance; } private Singleton(){ } }
- The solution of Bill Pugh 。- From wiki <Singleton Pattern> 。通过静态成员类来实现,线程安全。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class Singleton{ //private constructor prevent instantiation from other classes private Singleton(){} /** *SingletonHolder is loaded on the first execution of Singleton.getInstance() *or the first access to SingletonHolder.INSTANCE,not befor. */ private static class SingletonHolder{ public static final Singleton instance=new Singleton(); } private static Singleton getInstance(){ return SingletonHolder.instance; } }
转载于:https://www.cnblogs.com/matt123/archive/2012/06/26/2564393.html
最后
以上就是温婉爆米花最近收集整理的关于Singleton模式的五种实现的全部内容,更多相关Singleton模式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复