Singleton mode (singleton)

Source: Internet
Author: User

The singleton mode has the following characteristics:

  • A singleton class can have only one instance
  • A singleton class must create its own unique instance
  • The Singleton class must provide this instance to all other objects

A hungry man singleton mode: Because the constructor is a private type, this class is not inheritable

public class Eagersingleton {private static final Eagersingleton m_instance=new Eagersingleton ();/* Private default constructor */private Eagersingleton () {}/* static factory method */public static Eagersingleton getinstance () {return m_instance;}}

It can be seen that when this class is loaded, the static variable m_instance is initialized and the private constructor is called. At this point, the only instance of the Singleton class is created.

Lazy Singleton mode: Because the constructor is a private type, this class is not inheritable

public class Lazysingleton {private static  Lazysingleton m_instance=null;/* privately default constructor */private Lazysingleton () {}/* Static Factory method */synchronized public static Lazysingleton getinstance () {if (m_instance==null) {m_instance=new Lazysingleton ();} return m_instance;}}

The necessary condition for using singleton mode is that a system requires that only one instance of a class should use Singleton mode. If a class allows several different instances to coexist, then there is no need to use singleton mode.

Singleton mode (singleton)

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.