Design Pattern _ Singleton pattern

Source: Internet
Author: User

Explanation:

As the object Creation Mode [gof95], the singleton mode ensures that a class has only one instance, and the instance is automatically instantiated to the entire system. This class is called a singleton class.

Singleton mode highlights:

1. A class can only have one instance

2. It must create its own instance

3. It must provide this instance to the entire system.


The Singleton mode can be divided into two categories:

Lazy and hungry

The Code is as follows:

/*** Hunger means hunger. Create */public class Singleton {Private Static Singleton instance = new Singleton (); public static Singleton getinstance () {return instance ;}}
/*** The lazy style is very lazy. When used, you can create **/public class Singleton {Private Static Singleton instance; Public synchronized static Singleton getinstance () {return instance = NULL? New Singleton (): instance; // creates a variable that does not exist, and the multi-threaded member variables that can be modified require security }}

Usage:

1. Read resource files and use more objects without repeating new

2. Cache

Advantage: Memory saving

Disadvantage: no polymorphism

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.