A single-instance pattern of Java design patterns

Source: Internet
Author: User

Definition: If a class can always create only one instance, then this class is called a singleton class, and this design pattern is called a singleton pattern.

Within the spring framework, you can set all the generated Bean objects to singleton mode, just specify scope= "singleton" When you configure the Bean instance, or do not configure default as singleton mode.

We can create a small demo to demonstrate the implementation of the singleton pattern, just to make sure that the class can only create one instance, and we can use the permission modifier private to decorate the class's constructor.

Provides an interface for creating this class, which can only be modified with static, creating a member variable inside the class to hold the generated instance.

The code is as follows:

 Packagetest;classanmail{}classSinglelondemo {Private StaticSinglelondemo SD; PrivateSinglelondemo () {} Public StaticSinglelondemo single () {if(SD = =NULL) {SD=NewSinglelondemo (); }        returnSD; }} Public classsingledemo{ Public Static voidMain (string[] args) {Singlelondemo SD1=Singlelondemo.single (); Singlelondemo SD2=Singlelondemo.single (); System.out.println (SD1==SD2); }}

The output is true to indicate that an instance is being generated.

The singleton pattern is a widely used design pattern, and many frameworks have applications, and the factories in the following factory models require only a single instance.

Two advantages of using singleton mode:

1. Reduce the overhead associated with creating Java instances.

2, easy to track the life cycle of a single Java instance, instance status, and so on.

A single-instance pattern of Java design patterns

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.