Java design mode for beginners (I) ------ Singleton Design Mode

Source: Internet
Author: User

Singleton design mode refers to a class that only generates one object. The advantage is that it ensures that all objects access a unique instance. The specific implementation code is as follows: public class A {public static void main (String [] args) {B B B = B. get () ;}} Class B {private static B B = new B (); private B () {}public static B get () {peturn B ;}} as to why this program can generate only one object, we need to explain why we have written this program. First, when we want to generate an object, the first thing is to use the constructor of this class. As long as the constructor of a class can be called by the outside world, numerous objects of this class can be generated. So the first thing we do is to private the constructor. However, at this time, one of our class objects cannot be generated. At this time, we wrote a statement inside the class: private B B = new B (); with this statement, we can generate an object, but inside the class, we wrote the get () method to get it out, so we had the above program. After that, we should be able to understand why he can generate only one object, this is the singleton design mode.

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.