Design Mode-singleton instance

Source: Internet
Author: User

Design Mode-singleton instance

 

 

 

The Singleton mode is: Ensure a class has only one instance, and provide a global point of access to it. make sure that a class has only one instance and provides the instance to the entire system. The Singleton mode ensures that only one instance exists. Java has two forms:
Hungry Chinese singleton: class is instantiated when loaded.
Package com. zz. singleton;/*** hunger examples * @ author txxs **/public class HungrySingleton {// class is instantiated when loading private static HungrySingleton m_instance = new HungrySingleton (); // The constructor is privatized to prevent external users from directly instantiating private HungrySingleton () {}// obtain the Instance Object public static HungrySingleton getInstance () {return m_instance ;}} using the following methods ;}}

Lazy singleton: the object is instantiated only when the class is referenced for the first time.

 

Package com. zz. singleton;/*** LazySingleton example * @ author txxs **/public class LazySingleton {// The object is instantiated for the first time when the class is referenced. private static LazySingleton m_instance = null; // privatize the display of the constructor to ensure that the private LazySingleton () {}// method cannot be directly instantiated by the outside world, preventing the two threads from simultaneously accessing m_instancesynchronized public static LazySingleton getInstance () {if (m_instance = null) {m_instance = new LazySingleton ();} return m_instance ;}}

Advantages of Singleton mode:

 

1. There is only one instance to reduce memory expenses.

2. Reduce system performance overhead.

3. You can avoid simultaneous operations on the same resource.

Disadvantages of Singleton mode:

It is difficult to expand because subclass cannot be created.

Haha, I wrote a code by myself and referred to the great gods to learn from each other and make progress. Download

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.