5 of 23 Design Patterns in Java-Multiple patterns (multition pattern)

Source: Internet
Author: User

As the name implies, multiple cases are compared to a singleton pattern, which can have more than one finite instance, such as the following, can only have two instances.

Import java.util.ArrayList;
Import Java.util.Random;
Class Multition
{
Private final static int max_number=2;
private static arraylist<multition> amultitionarraylist=new arraylist<multition> ();
private static int index=0;
Private String Currentmultitioninfo;
Static
{
for (int i=0;i<max_number;i++)
{
Index=i;
Amultitionarraylist.add (New Multition ());
}
}
Private Multition ()
{
Currentmultitioninfo= "The current object is" +INDEX;
}
public static multition getinstance ()
{
Random arandom=new random ();
Index=arandom.nextint (Max_number);
Return Amultitionarraylist.get (index);
}
public void Printmultitioninfo ()
{
System.out.println (Currentmultitioninfo);
}
}

public class Multitionpatterntest
{
public static void Main (string[] args)
{
Multition Amultiton=null;
for (int i=0;i<10;i++)
{
Amultiton=multition.getinstance ();
Amultiton.printmultitioninfo ();
}
}
}

///////////////////////////////

Output Result:

The current object is 1
The current object is 1
The current object is 0
The current object is 1
The current object is 0
The current object is 0
The current object is 0
The current object is 0
The current object is 1
The current object is 0

5 of 23 Design Patterns in Java-Multiple patterns (multition 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.