建立型模式--多例模式,建立型--

來源:互聯網
上載者:User

建立型模式--多例模式,建立型--

多例模式通常被劃分為:有上限多例模式、無上限多例模式。

平時我們通過new一個對象的就是無上限多例模式。

什麼叫有上限多例模式,其實就是單例模式的推廣,建立>1個的執行個體(有限)。


代碼描述:

<span style="font-size:18px;">public class Case {//儲存有限個類的執行個體private static ArrayList<Case> caseList=new ArrayList<Case>();//建立執行個體的個數private static final int MAX_NUM=2;/* * 在類初試化階段執行靜態初始化快 */static{for(int i=0;i<MAX_NUM;i++){caseList.add(new Case());}}//私人方法private Case(){}//定義static,類所有public static Case getCase(){Random random=new Random();int count=random.nextInt(MAX_NUM);return caseList.get(count);}}</span>

在上面代碼中,通過靜態初始化塊建立了有限個類的執行個體,通過geCase()方法隨機擷取執行個體。


如果我們不想通過隨機擷取執行個體,而是指定第幾個執行個體的話,可以參看下面的代碼:


<span style="font-size:18px;">public class Case {//儲存有限個類的執行個體private static ArrayList<Case> caseList=new ArrayList<Case>();//建立執行個體的個數private static final int MAX_NUM=2;/* * 在類初試化階段執行靜態初始化快 */static{for(int i=0;i<MAX_NUM;i++){caseList.add(new Case());}}//私人方法private Case(){}//定義static,類所有public static Case getCase(final int index){if(index<MAX_NUM&&index>=0){return caseList.get(index);}return null;}}</span>


轉載請註明出處:http://blog.csdn.net/hai_qing_xu_kong/article/details/42207289    情緒控_


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.