Single case Mode singleton

Source: Internet
Author: User

In the development of the time, we in some cases some objects we only need one. For example: Configuration files, tool classes, thread pools, caches, log objects, and so on.

How do we ensure that we have only one object? We can do this by single example .

There are two common types of singleton: a hungry man mode and lazy mode.

  a hungry man mode : This singleton object is created when the class is loaded. (Load slower, but run faster, thread safe )

public class Singleton {//1. The construction method is set to private, the object of the class is not allowed to be instantiated directly by the outside world Private Singleton () {}//2. Create a private static instance object private static Singleton Instance = new Singleton ();//3. Obtaining an instance object through a common static method public static Singleton getinstance () {return instance;}}

Lazy Mode : Class loading does not create a singleton for the class, only the first time the getinstance () method is called, a singleton of the class is created. (Fast loading, runtime for first time slow, non-thread safe )

public class Singleton {//1. Sets the construction method to private and does not allow the outside world to instantiate objects directly from the class private Singleton () {}//2. Declares a unique instance of a class, using private static to modify private Static Singleton INSTANCE;//3. Get instance object public static Singleton getinstance () {if (instance = null) through a common static method {instance = New Singleton ();} return instance;}}

Single case 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.