Create mode -- Multi-instance mode, create mode --
The multi-sample mode is generally divided into the multi-sample mode with an upper limit and no upper limit.
We usually use the multi-sample mode with no upper limit to a new object.
What is the multi-sample mode with an upper limit is actually the promotion of the singleton mode. create more than one instance (limited ).
Code Description:
<Span style = "font-size: 18px; "> public class Case {// Save the private static ArrayList of instances with limited classes <Case> caseList = new ArrayList <Case> (); // The number of instances to be created is private static final int MAX_NUM = 2;/** perform static initialization fast during the class preliminary test */static {for (int I = 0; I <MAX_NUM; I ++) {caseList. add (new Case () ;}/// private method private Case () {}// defines static, class all public static Case getCase () {Random random = new Random (); int count = random. nextInt (MAX_NUM); return caseList. get (count) ;}}</span>
In the code above, an instance with limited classes is created through the static initialization block, and the instance is randomly obtained through the geCase () method.
If we do not want to randomly retrieve instances, but specify the instances, see the following code:
<Span style = "font-size: 18px; "> public class Case {// Save the private static ArrayList of instances with limited classes <Case> caseList = new ArrayList <Case> (); // The number of instances to be created is private static final int MAX_NUM = 2;/** perform static initialization fast during the class preliminary test */static {for (int I = 0; I <MAX_NUM; I ++) {caseList. add (new Case () ;}/// private method private Case () {}// defines static, class all public static Case getCase (final int index) {if (index <MAX_NUM & index> = 0) {return caseList. get (index) ;}return null ;}</span>
Reprinted please indicate the source: http://blog.csdn.net/hai_qing_xu_kong/article/details/42207289 sentiment control _