理解:多例模式相对单例模式来说,多例模式可以有多个实例,但是他们都不对外提供构造方法,构造方法都是私有private的。对应程序每一个请求都用一个新对象来处理,防止并发问题;线程池以及线程池资源复用功能;

    1. public class Emperor {
    2. private static final int maxNumberOfEmperor = 2;
    3. private static ArrayList emperorInfoList = new ArrayList(maxNumberOfEmperor);
    4. private static ArrayList emperorList = new ArrayList(maxNumberOfEmperor);
    5. private static int countNumofEmperor = 0;
    6. static{
    7. for(int i = 0; i < maxNumberOfEmperor ; i++){
    8. emperorList.add(new Emperor("第"+i+"皇帝"));
    9. }
    10. }
    11. private Emperor(){
    12. }
    13. private Emperor(String info){
    14. emperorInfoList.add(info);
    15. }
    16. public static Emperor getInstance(int num){
    17. countNumofEmperor = num;
    18. if (num == 0) {
    19. return (Emperor) emperorList.get(0);
    20. }else if(num == 1){
    21. return (Emperor) emperorList.get(1);
    22. }else{
    23. System.out.println("error");
    24. return null;
    25. }
    26. }
    27. public static Emperor getInstance(){
    28. Random random=new Random();
    29. countNumofEmperor=random.nextInt(maxNumberOfEmperor);
    30. return (Emperor)emperorList.get(countNumofEmperor);
    31. }
    32. @Override
    33. public String toString() {
    34. // TODO Auto-generated method stub
    35. return (String) emperorInfoList.get(countNumofEmperor);
    36. }
    37. }
    1. /**
    2. *多例模式
    3. *所谓多例(Multiton Pattern)实际上就是单例模式的自然推广,属于对象
    4. *创建类型的模式,多例模式其实就是限制了对象的数量,并且有可能对对象进行重复使用
    5. *
    6. *特点:
    7. *1:多例可以有多个实例
    8. *2:多例类必须能够自我创建并管理自己的实例,并且向外界提供自己的实例
    9. * @author Administrator
    10. *
    11. */
    12. public class MultiPatternTest {
    13. public static void main(String[] args) {
    14. Emperor mEmperor = Emperor.getInstance(0);
    15. System.out.println(mEmperor.toString());
    16. mEmperor = Emperor.getInstance(1);
    17. System.out.println(mEmperor.toString());
    18. mEmperor = Emperor.getInstance(2);
    19. }
    20. }