JAVA Implementation in multiton mode [00 original]

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.