Java single-Instance design pattern

Source: Internet
Author: User

/*
Single Case design mode
Problem solved: You can guarantee that a class is in memory for the uniqueness of the object (the data is shared).
How to ensure the uniqueness of the object?
1, do not allow other programs to use,
2, create an instance of this in this class.
3, to provide a way for other programs to get the image.
Steps:
1, privatize the class constructor.
2. Create an object in this class by using new.
3, define a public method that will create the object to return.
*/

public class Test1 {

public static void Main (string[] args) {
//TODO auto-generated method stub

Test5 t1=test5.getinstance ();
Test5 t2=test5.getinstance ();
System.out.println (t1==t2);
T1.setnum (ten);
T2.setnum (+);
System.out.println (T1.getnum ());
System.out.println (T2.getnum ());
}

}
Class Test5
{
int num;
private static TEST5 t=new Test5 ();
Private Test5 ()
{

}
public static TEST5 getinstance ()
{
return t;
}
public int Getnum () {
return num;
}
public void setnum (int num) {
This.num = num;
}
}

Execution Result:

True
100
100

Java single-Instance design pattern

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.