Introduced:
The so-called multi-case pattern, in fact, is a singleton pattern (look back here) of the natural extension, as the object of the creation mode, the multi-example mode has the following characteristics:
1 can have multiple instances
More than 2 classes must create themselves, manage their own instances, and provide their own instances to the outside world.
From the above features, it can be realized that the multi-case pattern and the singleton pattern are different. Singleton mode allows only one instance to exist.
A singleton class diagram:
Multi-sample class diagram:
Class diagram more intuitive representation of the multi-class, the multi-class will provide multiple instances, the number of instances we can control, if the number is not much, the instance can be regarded as the internal instance variables of the class, if there are many instances, you can use an array, or a variable-length array to store. The following is a high-limit example class.
There is a maximum number of classes:
The upper limit of the multi-class, the name is very clear white, the number of instances of the class is capped, usually this limit is controlled by the programmer. We use sieves to give examples.
I don't know if we play mahjong, I think Mahjong is a kind of leisure way for the masses in China. Maybe there's a little bit of a different play around. But generally playing mahjong requires a sieve. Sometimes the sieve is 1, sometimes two, and it can be 3. Here assume 2 sieves. Since the number of sieves is determined to be 2, this is a multiple class with a limit of 2.
Class diagram for the sample program:
Sample program code:
1234567891011121314151617181920212223242526272829303132 |
ImportJava.util.Random;class die{ PrivateStatic dieDie1=New die();//Sieve 1 PrivateStatic dieDie2=New die();//Sieve 2 Private die(){ //Private constructors Ensure that this class is not instantiated by the outside world } //Get Sieve method, similar to simple Factory mode, decide which sieve to return by tag PublicStatic dieGetdie(intTag){ if(Tag==1) returnDie1; if(Tag==2) returnDie2; returnNULL; } //Throw a sieve and return a random number of 1~6. PublicsynchronizedintDice(){ RandomRandom=NewRandom(); returnRandom.Nextint(6)+1; }} Public classMain{ PrivateStatic dieDie1,Die2; PublicStatic voidMain(String[]args){ Die1 = die.Getdie(1); Die2= die.Getdie(2); System. out.println("The value of sieve 1 is"+Die1.Dice()); System. out.println("The value of Sieve 2 is"+Die2.Dice()); }} |
No upper-bound multi-class: