Singleton Pattern)

Source: Internet
Author: User

Self-awareness: A single-piece model is like a "one-man-one-wife" in China's marriage system. A husband can only have one daughter-in-law. If you want to marry a second or third daughter-in-law, the civil affairs bureau will certainly not do it for you; while the single-piece mode is that an object can only create one instance. If you want to create the second and third instances, the program will prompt you "illegal ".

Purpose: The single-piece mode aims to provide a global access point for the program class.

Other methods and disadvantages:

A. Create A single piece at the beginning of the program and pass it as A parameter to the class that needs to be used.

Disadvantage: in a program running, you may not need all the single pieces, which will affect the program performance.

B. create a registry for all single-piece classes in the program and make the Registry always available. Each time a single piece is instantiated, it is recorded in the registry, all parts of the program can use identifiers to access any single-piece instance and retrieve corresponding instance variables.

Disadvantage: The type check is reduced, because the single-piece table in the registry may keep all the single-pieces as the object type, such as the object type in Hashtable. In addition, the Registry itself may also be a single-piece, you must use constructors or other set functions to pass all the parts of a program.

C. Static Method of the class.

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.