理解:多例模式相对单例模式来说,多例模式可以有多个实例,但是他们都不对外提供构造方法,构造方法都是私有private的。对应程序每一个请求都用一个新对象来处理,防止并发问题;线程池以及线程池资源复用功能;
public class Emperor {
private static final int maxNumberOfEmperor = 2;
private static ArrayList emperorInfoList = new ArrayList(maxNumberOfEmperor);
private static ArrayList emperorList = new ArrayList(maxNumberOfEmperor);
private static int countNumofEmperor = 0;
static{
for(int i = 0; i < maxNumberOfEmperor ; i++){
emperorList.add(new Emperor("第"+i+"皇帝"));
}
}
private Emperor(){
}
private Emperor(String info){
emperorInfoList.add(info);
}
public static Emperor getInstance(int num){
countNumofEmperor = num;
if (num == 0) {
return (Emperor) emperorList.get(0);
}else if(num == 1){
return (Emperor) emperorList.get(1);
}else{
System.out.println("error");
return null;
}
}
public static Emperor getInstance(){
Random random=new Random();
countNumofEmperor=random.nextInt(maxNumberOfEmperor);
return (Emperor)emperorList.get(countNumofEmperor);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return (String) emperorInfoList.get(countNumofEmperor);
}
}
/**
*多例模式
*所谓多例(Multiton Pattern)实际上就是单例模式的自然推广,属于对象
*创建类型的模式,多例模式其实就是限制了对象的数量,并且有可能对对象进行重复使用
*
*特点:
*1:多例可以有多个实例
*2:多例类必须能够自我创建并管理自己的实例,并且向外界提供自己的实例
* @author Administrator
*
*/
public class MultiPatternTest {
public static void main(String[] args) {
Emperor mEmperor = Emperor.getInstance(0);
System.out.println(mEmperor.toString());
mEmperor = Emperor.getInstance(1);
System.out.println(mEmperor.toString());
mEmperor = Emperor.getInstance(2);
}
}