首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

单例兑现方法

2012-11-01 
单例实现方法1.通过判断private Singleton(){}private static Singleton instance nullpublic static S

单例实现方法
1.  通过判断
    private Singleton(){}
    private static Singleton instance = null;
    public static Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }
   
2.  使用静态成员变量
    private Singleton(){}
    private static Singleton instance = new Singleton();
    public static singleton getInstance(){
        return instance;
    }

3.  利用缓存
    private Singleton(){}
    private Map<String,Singleton> map = new HashMap<String,Singleton>;
    public Singleton getInstance(String key){
        singleton instance = map.get(key);
        if (instance == null ){
            instance = new Singleton();
            map.put(key,instance);
        }
        return instance;
    }
   
4.  为1添加线程安全:同步
     public static synchronized Singleton getInstance(){
           ....
    }
      
5.  双重检查加锁
    private Singleton(){}
    private volatile static Singleton instance = null;
    public static Singleton getInstance(){
        if (instance == null){
            synchronized(this){  //synchronized(Singleton.class)
                if (instance == null){
                    instance = new Singleton();
                }
            }
        }
    }

6. 通过静态内部类: 比较好的实现方式(既实现了延迟加载,也保证了线程安全)
    private static class SingletonHolder{
        private static Singleton instance = new Singleton();   
    }
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }

7. 枚举: 最佳实现
    enum SingletonEnum {

       singleton;

       //构造器
        private SingletonEnum(){
            System.out.println("构造器只调用一次");
       }
       //属性
        private String attribute;
       //定义方法
        public void method(){}
   }
   
       

热点排行