首页 > 其他 > 详细

单例模式

时间:2015-04-22 00:38:08      阅读:132      评论:0      收藏:0      [点我收藏+]

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一,属于创建型模式。
单例模式定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

单例模式的使用场景: 比如要求产生唯一序列号; 比如创建的对象需要消耗的资源过多,如 I/O 与数据库的连接等。

单例模式的特点:①构造函数是私有的;②单例类只能有一个实例。其实②是①的结果。

通常可以使用下面的几种方式创建单例模式(Java参考代码):
懒汉式(同步效率比较低):

public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

饿汉式(每次创建对象,比较浪费资源):

public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}

双重校验锁:

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

最后想说的是,其实枚举类也是一种单例模式。在Java中没有枚举类型的时候,就是用单例模式模拟枚举类型的。

单例模式

原文:http://blog.csdn.net/theonegis/article/details/45180317

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!