單例類和單例註冊表的實現

來源:互聯網
上載者:User

1,單例類的實現. 可以保證在非同時多線程多類載入器的環境下的單例

public class Singleton...{
    private static Singleton instance;
    
    //私人化構造方法來防止外部通過new 來建立該類的執行個體
    private  Singleton ()...{
        
    }    
    //使用 synchronzied 保證安全執行緒
    public synchronized static Singleton getInstance()...{
        if(instance==null)...{
            instance= new Singleton();
        }
        return instance;
    }
    
}

2.單例註冊表的實現. 用於操作一組對象的聚集

import java.util.*;


public class SingletonRegistry...{
    private static SingletonRegistry instance;
    private static Map factoryMap = new HashMap();
    
    //私人化構造方法
    private SingletonRegistry()...{
        
    }
    
    public synchronized static  SingletonRegistry getInstance()...{
        if(instance==null)...{
            instance = new SingletonRegistry();
        }
        return instance;
    }
    
    
    public synchronized BeanFactroy getBeanFactory(String factoryName)...{
        BeanFactroy f=null;
        //在註冊表中尋找看是否有這個BeanFactory的執行個體
        Object o = factoryMap.get(factoryName);
        
        if(o!=null)...{
            return (BeanFactroy)o;
        }
    
        try ...{
        f= (BeanFactroy)Class.forName(factoryName).newInstance();
            
            //將Bean工廠註冊到註冊表
            factoryMap.put(factoryName,f);
            
            
        }
        catch (Exception ex) ...{
            ex.printStackTrace();
        }
        return f;
        
    }
    
}

interface BeanFactroy...{
    
}


/**//*一個單例類,通過Map持有BeanFactory的對象聚集。SingletngRegistry本身只有一個執行個體 但是
 *它可以持有任意多個BeanFactory的執行個體
 */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.