Design mode-simplest design pattern singleton mode

Source: Internet
Author: User

Singleton mode: The simplest design mode

Role: is to ensure that in the entire application lifecycle, at any one time, instances of the Singleton class exist only one.

Divided into two a hungry man modes and lazy mode

A hungry man mode: When the class loads slowly but gets the object fast

public class Singleton {
The role of privatization of constructors is not to allow the creation of Singleton instances in new ways in other classes
Private Singleton () {
}
This guarantees that there can be only one instance in the global
private static Singleton Singleton = new Singleton ();
This is a package.
public static Singleton Getsingleton () {
return singleton;
}

}

Lazy mode: When the class loads faster, but gets the object slowly

public class Singleton {
The role of privatization of constructors is not to allow the creation of Singleton instances in new ways in other classes
Private Singleton () {
}
private static Singleton Singleton;
This is the encapsulation. This guarantees that there can be only one instance in the global
public static Singleton Getsingleton () {
if (singleton==null) {
Singleton = new Singleton ();
}
return singleton;
}

}

Design mode-simplest design pattern singleton mode

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.