码迷,mamicode.com
首页 > 编程语言 > 详细

java中23种设计模式之5-多例模式(multition pattern)

时间:2015-03-30 21:03:30      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

顾名思义,多例模式相对于单例模式,就是可以有多于一个的有限实例,如下列,只能有两个实例。

 

import java.util.ArrayList;
import java.util.Random;
class Multition
{
private final static int MAX_NUMBER=2;
private static ArrayList<Multition> aMultitionArrayList=new ArrayList<Multition>();
private static int index=0;
private String CurrentMultitionInfo;
static
{
for(int i=0;i<MAX_NUMBER;i++)
{
index=i;
aMultitionArrayList.add(new Multition());
}
}
private Multition()
{
CurrentMultitionInfo="the current object is "+index;
}
public static Multition getInstance()
{
Random aRandom=new Random();
index=aRandom.nextInt(MAX_NUMBER);
return aMultitionArrayList.get(index);
}
public void printMultitionInfo()
{
System.out.println(CurrentMultitionInfo);
}
}

public class MultitionPatternTest
{
public static void main(String[] args)
{
Multition aMultiton=null;
for(int i=0;i<10;i++)
{
aMultiton=Multition.getInstance();
aMultiton.printMultitionInfo();
}
}
}

///////////////////////////////

输出结果:

the current object is 1
the current object is 1
the current object is 0
the current object is 1
the current object is 0
the current object is 0
the current object is 0
the current object is 0
the current object is 1
the current object is 0

java中23种设计模式之5-多例模式(multition pattern)

标签:

原文地址:http://www.cnblogs.com/wudymand/p/4378987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!