Design Mode-singleton mode, design mode-Mode

Source: Internet
Author: User

Design Mode-singleton mode, design mode-Mode

The Singleton mode is a relatively simple mode in the design mode. It is mainly used to ensure that only one class instance exists in the program, so it is called a singleton.

This is similar to an enumeration class. An enumeration class is an instance of a limited number of classes. In extreme cases, that is, the finite number of enumerations is 1, which is the singleton mode.

The following describes two methods for a singleton:

  • Lazy: As the name implies, a class instance is created when the class is loaded.
  • Hungry Chinese Style: The instance is created only when the method is called, and there is a thread security problem.
// Hungry Chinese public class Singleton {// 1. private Singleton () {}// 2. create an instance internally and privatize private static Singleton instance = new Singleton (); // 3. set the get method to allow external instances to be created and set to static. The corresponding member variables are also declared as static public static Singleton getInstance () {return instance ;}}

Note the following:

// Lazy public class Singleton1 {private Singleton1 () {} private static Singleton1 instance = null; public static Singleton1 getInstance () {// generally, this parameter is not created, it is created only when the instance is called and the instance is null. // thread security issues may exist. if (instance = null) {instance = new Singleton1 ();} return instance ;}}

The difference from the hunger style is the instance creation time.

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.