Design Patterns--single case

Source: Internet
Author: User

Thrust

Ensure that there is at most one instance of a type for the entire program life cycle

Applicable scenarios

A system can create multiple print tasks, but only one print task is supported at the same time

Characteristics

1, the Singleton class can have only one instance.
2, the Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.

Classification

The common singleton pattern is divided into two kinds of a hungry man and lazy type.

1. A Hungry man mode

public class singleton{

private static Singleton _instance=new Singleton ();

Private Singleton () {};

public static Singleton getinstance () {

return _instance;

}

}

Since the JVM created the Singleton class and also created a static singleton instance, the pattern is inherently thread-safe

2. Lazy mode (double check lock)

public class singleton{

private static Singleton _instance;

Private Singleton () {}

Public Singleton getinstance () {

if (_instance==null) {

Synchronized (Singleton.class) {

if (_instance==null) {

_instance=new Singleton ();

}

}

}

return _instance;

}

}

Because of this pattern in order to ensure thread-safe use of synchronized efficiency is reduced, but also before the use of synchronized a layer of judgment, a certain level of shielding synchronized execution

3. Lazy mode (Static inner Class)

public class Singleton {
private Static Class Lazyloader {
Private static final Singleton instance = new Singleton ();
}

Private Singleton () {
}

public static Singleton getinstance () {
return lazyloader.instance;
}
}

Because the instance member of the static inner class Lazyloader is instantiated only when it is first called

Design Patterns--single case

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.