design mode (i) __ Single-Instance design mode

Source: Internet
Author: User

First to introduce what is the design pattern, design patterns from the construction industry for reference, and then slowly developed into today's appearance.

Design pattern is the most effective way to solve the problem , is a set of repeated use, most people know, through the classification purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability.

Java has 23 design patterns, let's start with one of these: a single-case design pattern

Single Case design mode:

Sometimes when you need to ensure that a class is in memory for object uniqueness , such as when multiple programs read a configuration file, it is recommended that the configuration file be encapsulated as an object. It is convenient to manipulate the data, and to ensure that multiple programs read the same profile object, it is necessary that the configuration file object is unique in memory. Then you need to use a singleton design pattern.

So, how to guarantee the uniqueness of the object?

Thought:

      1. Do not allow other classes to create the class object.
      2. Create an object of this class in this class
      3. Provide a way for other programs to get this object

Steps:

1. Because creating objects requires constructor initialization, you only need to privatize the constructors in this class so that other classes cannot create the class object.

2. Create an object of this class in this class

3. Define a public method that returns the object for other classes to access. (Effect: controllable)

Well, the above on the single-case mode of thinking to everyone to say, the single-case pattern of several types, here are mainly introduced two kinds: Lazy type single case, a hungry man type single case.

One: a hungry man type

class Single {    private//  privatized constructor. private    staticfinalnew//  creates a proprietary and static object of this class.     publicstatic//  defines a publicly-owned and static method that returns the object.         return  s;    }}

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.

Two: Lazy type

class Single {    private  single () {}    privatestaticnull;    Public static single getinstance () {        ifnull)             New Single ();         return s;    }}

However, the above-mentioned lazy singleton implementation does not take into account the thread safety problem, it is thread insecure, the concurrency environment is likely to appear multiple single instances, to achieve thread safety, can be resolved by multiple judgment plus synchronization.

classSingle {PrivateSingle () {}; Private StaticSingle S =NULL;  Public StaticSingle getinstance () {if(s = =NULL) {            synchronized(Single.class) {                if(s = =NULL) {s=NewSingle (); }            }        }        returns; }}

Three: A hungry man and lazy-type difference

A hungry man is more urgent, once the class is loaded, the singleton initialization is completed.

Laziness is too lazy to initialize this singleton only when calling GetInstance.

Ii

A hungry man is inherently thread-safe and can be used directly for multithreading without problems.

The lazy type itself is non-thread safe.

A hungry man a static object is instantiated at the same time as the class is created, and will occupy a certain amount of memory regardless of whether the singleton will be used later, but correspondingly, the speed will be faster on the first call because its resources have already been initialized.

And as the lazy name implies, it will delay loading, the first time to use the singleton will be instantiated objects out, and because of thread safety problems, need to add synchronization, efficiency is relatively low.

design mode (i) __ Single-Instance design 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.