Design Mode-singleton mode, design mode-Mode

Source: Internet
Author: User

Design Mode-singleton mode, design mode-Mode

Singleton mode-hunger Mode

1. privatize the constructor and do not allow external users to directly create private Singleton (){}
2. Create a unique instance private static Singleton instance = new Singleton () within the class ();
3. Provide a public static Singleton getInstance () {return instance} method for obtaining an instance };

public class Singleton{ private static Singleton instance=new Singleton(); private Singleton(){}
public staitc Singleto getInstance(){   return instance; } }

 

Singleton mode-Lazy Mode

1. constructor privatization

2. Create a static member variable for a unique instance of the class (null)

3. The difference between creating a static member for a single instance is the time when the instance is generated (when the class is loaded or when the class is used)

public class Singleton{ private Singleton(){}private static Singleton instance; public static Singleton getInstance(){   if(instance==null){ 
    return new Singleton();
  } else {
    return instance;
   }
}

 

Differences:
Hungry Chinese: declarations are directly instantiated at the same time. Features: the loading process is slow, but the process of getting objects at run time is fast and thread safety.
Lazy: Do not instantiate the statement. Features: It is faster to load classes, but it is slower to get objects during running, and the thread is not secure.

 

Related Article

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.