This example is used to show how to roll the dice.
1. Class Diagram
2. Java implementation code
Package cn.edu. ynu. Sei. multiton;
/**
* Customers who use dice
*
* @ Author 88250
* @ Version 1.0.0, 2007-8-19
*/
Public class client
{
Private Static die die1, die2;
/**
* Program entry point
* @ Param ARGs should be <code> null </code>
*/
Public static void main (string [] ARGs)
{
Die1 = die. getinstance (1 );
Die2 = die. getinstance (2 );
System. Out. println (die1.dice ());
System. Out. println (die2.dice ());
}
}
Package cn.edu. ynu. Sei. multiton;
Import java. util. date;
Import java. util. Random;
/**
* Dice, implemented in Multi-sample mode
*
* @ Author 88250
* @ Version 1.0.0, 2007-8-19
*/
Public class die
{
Private Static die die1 = new die ();
Private Static die die2 = new die ();
/**
* The private constructor ensures that the class cannot be directly instantiated from the outside.
*/
Private die (){};
/**
* Factory Method
* @ Param whichone dice number
* @ 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;
}
}
3. Summary
From the multi-sample mode, we can see that the singleton mode is actually a special case. In the code, we use the "Hungry Chinese" method to implement instantiation. When using the multi-sample mode, we should pay attention to the same things as the singleton mode. Attention should be paid in Distributed Systems and multi-threaded environments. For the reason, refer to the JAVA Implementation of Singleton [00 original].
4. References
Design Patterns and Java and Pattern