Java Singleton Pattern Singleton Mode

Source: Internet
Author: User

Java Singleton Pattern Singleton Mode

Wikipedia: When you click open link to apply this mode, the class of the singleton object must ensure that only one instance exists.

Key points:

1. private constructor-other classes cannot instantiate a new object.
2. Private reference-External modification is not allowed.
3. The public static method is the only way to obtain objects.



Public class SingleObject {private static SingleObject instance = new SingleObject (); // create an object of SingleObjectprivate SingleObject () {}// private constructor, therefore, the public static SingleObject getInstance () {// provides a static method to get its static instance to outside world. return instance;} public void showMessage () {System. out. println ("Hello world... ");}}


Public class SingletonPatternDemo {public static void main (String [] args) {// SingleObject object = new SingleObject () // invalid constructor SingleObject () is not visibleSingleObject object = SingleObject. getInstance (); // Get the only object availableobject. showMessage ();}}

Output result: Hello world...


More learning, especially,Singleton mode in multi-threaded Environments, Click:

Wikipedia-http://zh.wikipedia.org/wiki/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F

Story telling, learning (Java) design mode-singleton mode click to open the link


Http://zz563143188.iteye.com/blog/1847029


References:

Http://www.tutorialspoint.com/design_pattern/design_pattern_quick_guide.htm



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.