标签:安全 instance null get new 常见 检查 on() 创建
单例模式是一种常见的设计模式
单例模式有以下特点:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
饿汉式单例
public class Singleton { private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } }
在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变
懒汉式单例
public class Singleton { private static Singleton instance = null; /** * 懒汉模式一 * 同步方法 */ public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } /** * 懒汉模式二 * 同步代码块 */ public static Singleton getInstance() { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } return instance; } }
同步代码,或者同步代码块,效率低
双重锁检查
public class Singleton { private static volatile Singleton instance = null; public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
线程安全,提高效率
内部静态类
public class Singleton { private static class SingletonHandler { private static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHandler.instance; } }
标签:安全 instance null get new 常见 检查 on() 创建
原文地址:http://www.cnblogs.com/alex09/p/6649740.html