- 单例模式的五种实现方式
- 发布时间:2016/1/11 来源:搜数网络 浏览:25
单例模式可以说是23中设计模式中应用最广的一种模式了。
定义:确保某一个类只有一个实例,自行实例化并且想整个系统提供这个实例。
使用场景:避免某个类产生多个对象而消耗过多的资源,确保某个类在程序中只有一个实例。比如我们使用的图片加载器ImageLoader。往往单例创建的对象,耗费的资源都比较多,所以在初始化单例对象的时候就显得尤为重要了,接下来,我们就来聊一聊单例的几种实现方式。
一、饿汉式
- public class ImageLoader{
- private static ImageLoader instance = new ImageLoader;
- private ImageLoader(){}
- public static ImageLoader getInstance(){
- return instance;
- }
- }
二、懒汉式
- public class ImageLoader{
- private static ImageLoader instance;
- private ImageLoader(){}
- public static synchronized ImageLoader getInstance(){
- if(instance == null){
- instance = new ImageLoader();
- }
- return instance;
- }
- }
三、Double CheckLock实现单例
英文稍好点的东西,应该都看懂了,DCL也就是双重锁判断机制,直接上代码。
- public class ImageLoader{
- private static ImageLoader instance;
- private ImageLoader(){}
- public static ImageLoader getInstance(){
- if(instance == null){
- synchronized (ImageLoader.class){
- if(instance == null){
- instance = new ImageLoader();
- }
- }
- }
- return instance;
- }
- }
四、静态内部类实现模式
直接上代码
- public class ImageLoader{
- private static class InnerInstance{
- private static final ImageLoader instance = new ImageLoader();
- }
- private ImageLoader(){}
- public static ImageLoader(){
- return InnerInstance.instance;
- }
- }
可以发现这种方式,并未加锁,因为第一次加载ImageLoader类时,并不会实例化单例对象,只有第一次调用getInstance()方法时会导致虚拟机加载InnerInstance类,这种
方式不仅能保证对象的单一性,还避免加锁带来的性能问题,又启动了延迟加载的优化,所以这就是单例模式的终极实现版本,也是推荐使用的方式。
原文地址:http://blog.csdn.net/soul_code/article/details/50183765