Java single-Instance design pattern

Source: Internet
Author: User

Singleton design pattern (that is, a class has only one object in memory)
Ideas:
1. Privatize the constructor
2. Create an object yourself in the class
3. Provides a way to get the object
Cases:
public Class A single {
Singleton design pattern (a class that only has one object in memory)
Private single () {///is set to proprietary so that it cannot be new out of the object
}
private static single s=new single (); Customizing an Object
public static single getinstance () {//Use (class name. static function) to return the object that you defined
return s;
}



private int age;
public void Setage (int.) {
This.age=age;
}
public int getage () {
return age;
}

}





The use of the Main method
Single s6=single.getinstance ();//Returns the custom object by (class name. static function)
Single s2=single.getinstance ();//Returns the custom object by (class name. static function)
S6.setage (36);

System.out.println (S2.getage ()); Print out 36, indicating that only one object exists in memory

System.err.println (S6);//The address value of the object is the same
SYSTEM.OUT.PRINTLN (S2);//The address value of the object is the same

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.