标签:
顾名思义,多例模式相对于单例模式,就是可以有多于一个的有限实例,如下列,只能有两个实例。
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