Java implementation of multiple example (Multiton) mode [00 original]__java

Source: Internet
Author: User
This example is carried out with the example of a roll of 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, using a number of model implementations
*
* @author 88250
* @version 1.0.0, 2007-8-19
*/
public class Die
{
private static Die Die1 = new Die ();
private static Die Die2 = new Die ();

/**
* Private constructor, which guarantees that the external cannot instantiate the class directly
*/
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, return a random number between the 1~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. SummaryA case-by-case pattern can be seen in a single example. In the code, we use the "a Hungry Man-style" method to implement the instantiation. In the use of multiple patterns we should be aware of the same things as the single case pattern. In the Distributed system and multi-threaded environment should be noticed, the reason for this refer to a single example (Singleton) Java implementation [00 original]
4. Reference Documents"Design Patterns", "Java and Mode"
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.