One of the Java Advanced Design Patterns-----a singleton pattern

Source: Internet
Author: User
Tags volatile

Objective

In just learn programming not long to hear the design model of the name, but because at that time was a thoroughly bottom rookie, and did not touch. It was not until the simple business code became familiar with the initial work that the design pattern was formally approached. At that time the first contact design mode is the Factory mode , but this article is about the Singleton model , here is left in the next article in the explanation. Why do you first explain the singleton mode ? That's because the singleton mode is the simplest in design mode .... There is always a sequence of things, so it's easier to get ahead. Well, the nonsense is not much to say, began to enter the positive.

Introduction to Design Patterns

Description: The introduction here is really "introduction".

What is design mode

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary.

Why design patterns are used

Design patterns are used to reuse code, make code easier for others to understand, and ensure code reliability.

Design pattern Type

There are 23 types of design patterns. According to the main classification can be divided into three major categories:

First, the creation mode

These design patterns provide a way to hide the creation logic while creating the object, rather than instantiating the object directly with the new operator. This allows the program to be more flexible when judging which objects need to be created for a given instance.

    • Single-Case mode
    • Factory mode
    • Abstract Factory mode
    • Builder mode
    • Prototype mode

Second, structural type mode

These design patterns focus on the combination of classes and objects. The concept of inheritance is used to combine interfaces and define how composite objects acquire new functionality.

    • Adapter mode
    • Bridging mode
    • Filter mode
    • Combination mode
    • Adorner mode
    • Appearance mode
    • Enjoy meta mode
    • Proxy mode

Iii. Behavioral Patterns

These design patterns pay particular attention to communication between objects.

    • Responsibility chain Model
    • Command mode
    • Interpreter mode
    • Iterator mode
    • Broker mode
    • Memo Mode
    • Observer pattern
    • State mode
    • Empty object mode
    • Policy mode
    • Template mode
    • Visitor mode
Principles of Design patterns

Six principles of design patterns

    1. Opening and closing principle: open to expansion, closed for modification.
    2. The principle of substitution of the Richter scale: The complementary principle of closure. Where any base class can appear, subclasses must be able to appear. The LSP is the cornerstone of inheritance reuse, and the base class can be reused only if the derived class is able to replace the base class and the functionality of the Software Unit is not affected, and the derived class can also add new behavior on the base class.
    3. Dependency reversal principle: Programming for interfaces depends on abstraction and not on specifics.
    4. Interface Isolation principle: Try to use multiple isolated interfaces, in order to reduce the degree of coupling between classes.
    5. Dimitri rule: An entity should interact with other entities as little as possible, making the system function modules relatively independent.
    6. Synthetic multiplexing principle: use synthetic/aggregated methods as much as possible, rather than using inheritance.
Singleton mode What is a singleton mode

Ensure that a class in a system has only one instance and that the instance is easily accessible to outsiders. For example, the task manager of the Windows interface can be seen as a single case.

Usage scenarios for single-instance mode

In the program, the database connection pool , thread pool , log Object and so on are more commonly used.

Singleton mode use

At the earliest, when we were learning the singleton model , we basically contacted the two modes: a hungry man style and full-Chinese style (lazy type).
Let's take a look at the implementation of these two patterns first.

A Hungry man type
Defines a private construction method, sets its instance object to a private property, adds the static and final modifiers, and then returns the instance through a public static method call.

 class SingletonTest1 {      private SingletonTest1() {      }      private static final SingletonTest1 instance = new SingletonTest1();      public static SingletonTest1 getInstance() {          return instance;      }  }

Full-Chinese style
Define a private constructor, define a static private variable of the class, then define a public static method, empty-judge the value of the class, do not return directly to NULL, or rebuild one.

class SingletonTest2 {     private SingletonTest2() {        }        private static SingletonTest2 instance;        public static SingletonTest2 getInstance() {            if (instance == null) {            instance = new SingletonTest2();        }            return instance;        }    }  

This is a simple introduction to these two patterns, and then let's look at the pros and cons of both.
A Hungry man type

    • Pros: It is simple to write and does not cause thread insecurity due to synchronized keywords.
    • Disadvantage: When the class is loaded, the instance and static variables are initialized and created and allocated memory space, and memory is always occupied.

Full-Chinese style

    • Advantages: It is simple to write, it is initialized at the first call and saves memory.
    • Disadvantage: Threads are unsafe and multiple threads may appear multiple instances of a call.
    • Summary: Easy to write, thread insecure, and efficient.

Although the full-han style can be added by adding the synchronized keyword to ensure thread safety. But the efficiency method is not said to be optimal.

Here is a description of the two best ways of writing before JDK1.5, one is static inner class and the other is double lock check .

Static Inner class
Define a private constructor, define a private static inner class for that class, and then define a static variable for that class in the inner class, and then return the instance through a public final decorated static method call.

  class  SingletonTest4 {      private SingletonTest4(){        }       private static class SingletonTest5{           private static SingletonTest4 instance = new SingletonTest4();        }        public static final SingletonTest4 getInstance(){            return SingletonTest5.instance;        }   }

Because the inner class of the class is private, it is inaccessible except public static methods GetInstance (), which are published externally. Because it is a lazy load, it does not synchronize when reading the instance, it has little performance flaws, is thread-safe, and is not dependent on the JDK version.

Double lock Check
Defines a private construction method, defines a static private variable by means of volatile , guarantees the visibility of the variable, and then defines a common static method, the first time the object is instantiated or not, is not null and direct return, improve efficiency; Synchronized synchronizes a block of code to prevent the object from being initialized when it is created again after the first creation of the object, and then the second time the object is instantiated or not, if it is uninitialized, the instance is returned directly.

  class SingletonTest6 {         private SingletonTest6() {         }           private static volatile SingletonTest6 instance;          public static SingletonTest6 getIstance() {             if (instance == null) {                synchronized (SingletonTest6.class) {                    if (instance == null) {                        instance = new SingletonTest6();                       }                   }               }               return instance;           }       }  

This model can be said to be optimal over a long period of time, with low memory footprint, high efficiency, thread safety, and multi-threaded operation atomicity. But one drawback is that writing trouble is not very friendly to novices.

JDK1.5 after the enumeration, and perfectly support the singleton mode, and thread safety, high efficiency! But these are not the most important, the most important thing is to write super simple! How simple, see the following example should be able to understand ...

Enumeration single Example

 enum SingletonTest7{        INSTANCE;     }

Right, you have not read wrong, this code, the other do not need ...
Enumerations need to be in the post-JDK1.5 version, which provides a free serialization mechanism, which absolutely prevents multiple instantiations, even in the face of complex serialization or reflection attacks. This approach is also advocated by effective, the Java author, Josh Bloch.

Summarize

There are several uses of the singleton pattern, so let's summarize what we need to pay attention to using the singleton pattern (not including enumerations).

    1. Construction method Privatization (private);
    2. Defines a private (private) static instantiation object;
    3. Provides a public static (static) method to obtain this instance;

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

One of the Java Advanced Design Patterns-----a singleton pattern

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.