The multi-instance mode has an upper limit for multiple instance classes and a upper limit for the mode.
Multiple instance classes with an upper number of instances have considered the upper limit of instances as part of the logic and built the interior of multiple instance classes. This mode is called the multi-instance mode with an upper limit.
For example, two dice are required for each Mahjong board, so the dice should be a dual-state type. Here we take this system as an example to describe the structure of the Multi-sample mode.
Figure 1:
The source code of multiple Die types is as follows:
Package Multiton; import java. util. date; import java. util. random; public class Die {private static Die die1 = new Die (); private static Die die2 = new Die (); /*** private constructor ensures that this class cannot be directly instantiated by the outside world */private Die () {}/*** factory Method * @ param whichOne * @ return */public static Die getInstance (int whichOne) {if (whichOne = 1) {return die1 ;} else {return die2;}/*** roll the dice and return one in 1 ~ Random Number between 6 * @ return */public synchronized int dice () {Date d = new Date (); Random r = new Random (d. getTime (); int value = r. nextInt (); value = Math. abs (value); value = value % 6; value + = 1; return value ;}}
In the multi-sample Die class, two Die instances are created in the hunger mode. According to the parameters of the static factory method, the factory method returns the dice () of the Die () object of one of the two instances () method
This method returns 1 ~ The random number between 6 is equivalent to the number of dice, as shown in the code list:
package Multiton;public class Client {private static Die die1,die2;public static void main(String[] args) {die1=Die.getInstance(1);die2=Die.getInstance(2);die1.dice();die2.dice();}}
Because the maximum number of instances is exceeded for multiple instance classes, when the maximum number of multi-instance classes is 1, multiple instance classes return to the singleton class, multi-class is the promotion of single-class,
The Singleton class is a special case of multiple instance classes.
A multi-instance class with an upper limit can use static variables to store all instances, especially when the number of instances is small, you can use static variables to store instances one by one.
In most cases, you need to use static aggregation to store these instances.
As shown above, the multi-sample mode has an upper limit of Multi-sample classes.