单例模式

来源:互联网 发布:屏幕触摸检测软件 编辑:程序博客网 时间:2024/06/05 10:39

1.双重检查锁定(double checked locking)

public class Singleton implements Serializable{ /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */private volatile static Singleton instance = null;/* 私有构造方法,防止被实例化 */private Singleton() {} /* 静态工厂方法,创建实例 */ public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();} }}return instance;}/* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */ private Object readResolve() {return instance;}}

2.静态工厂

private static Singleton uniqueInstance;    private Singleton(){}    public static Singleton getInstance() {if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;}

或者

private static final Singleton uniqueInstance = new Singleton();    private Singleton(){}    public static Singleton getInstance() {return uniqueInstance;}


3.静态内部类

  1. public class Singleton {    
  2.     private static class LazyHolder {    
  3.        private static final Singleton INSTANCE = new Singleton();    
  4.     }    
  5.     private Singleton (){}    
  6.     public static final Singleton getInstance() {    
  7.        return LazyHolder.INSTANCE;    
  8.     }    
  9. }   

4.枚举


public enum Singleton {INSTANCE;}

使用枚举的原因:

1.枚举单例可以自己处理序列化

2.保证只有一个实例(即使使用反射也无法多次实例化一个枚举量)

3.线程安全



0 0
原创粉丝点击