A single-instance pattern of Java design patterns

Source: Internet
Author: User

Design Patternsare a set of reusable, most known, categorized 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. There is no doubt that the design pattern in others in the system are multi-win; Design patterns make code programming truly engineering; Design patterns are the cornerstone of software engineering, like the structure of a building (Baidu Encyclopedia).

Design Pattern Classification:

Create Model:

Singleton mode, Factory mode, abstract Factory mode, builder mode, prototype mode

Structural mode:

Adapter mode, bridge mode, trim mode, combo mode, appearance mode, proxy mode

Behavior pattern:

Responsibility chain mode, Command mode, strategy mode, observation mode, interpreter mode, iteration mode, mediation mode, Memo mode, state mode, template mode, visitor mode

Design principles

Opening and closing principle: a software entity should be open to the extension to modify the closure.

The principle of substitution of the Richter scale: any place that can use the parent class must be able to use subclasses.

Dependency reversal principle: to rely on abstraction do not depend on implementation. Or the abstraction should not be dependent on the details, the details should be dependent on abstraction.

Synthetic aggregation multiplexing principle: use synthetic aggregation instead of inheritance to achieve reuse as much as possible.

Dimitri rule: A software entity should interact with as few interactions as possible with other entities.

Interface Isolation principle: The client should be provided with the smallest possible individual interface and should not provide a large integrated interface.

Today I learned the singleton mode.

The core role of the Singleton model

Guarantees that a class has only one instance and provides a global access point to access the instance. means that there is only one object that exists.

Advantages of a single case:

Generate only one instance, reducing system overhead and improving system performance.

Provides a global access point for resource sharing.

Advantages of a single case:

Poor extensibility.

The abuse of a single case will bring some negative problems, such as a singleton class designed to conserve resources for the database connection pool object, which could result in a connection pool overflow for programs that share connection pool objects, and if the instantiated objects are not exploited for a long time, the system is considered garbage and is recycled, which results in the loss of the object state.

Common Application Scenarios:

The class of the read configuration file commonly used in code, we will only have one object. It is not necessary to create a new object every time an object is read.

Windows Task Manager, how to press will only one out.

Log objects, we will generally use a singleton.

Common 5 Types of singleton mode implementations:

Main:

A Hungry man (thread-safe, high-efficiency invocation.) Cannot delay loading to space for time).

Lazy type (thread safety, call efficiency is not high, can delay loading time to change space).

Other:

Dual detection Lock ("unordered write" problem with JVM memory is not recommended)

static internal class (thread safety, high call efficiency, delay loading)

Enumeration Singleton (thread safety, high call efficiency, no delay loading)

Lazy Single-Case:

 PackageCom.roc.singlet;/*** Lazy Type single case *@authorLIAOWP **/ Public classSingletPatter1 {//the object is loaded immediately when the class is initialized. Thread safety when the class is loaded. Private StaticSingletPatter1 instance =NewSingletPatter1 ();PrivateSingletPatter1 () {} Public StaticSingletPatter1 getinstance () {returninstance;}}

Lazy Type:

 PackageCom.roc.singlet;/*** Lazy-type (thread safety, call efficiency is not high, can delay loading time to change space, object delay loading). * @authorLIAOWP **/ Public classSingletPatter2 {//The object was not created immediately when initialized. Private StaticSingletPatter2 instance;//Private Session ConstructorPrivateSingletPatter2 () {} Public Static synchronizedSingletPatter2 getinstance () {if(instance==NULL) {instance=NewSingletPatter2 ();}returninstance;}}

Main Features: Lazy loading (delay loading) when used to load.

There is a problem: Synchronize every time, low concurrency efficiency.

How to understand 2 Types of single cases:

A hungry man: think of you hungry when you want to go to eat immediately, load, this is a hungry man.

Lazy: im hungry, but lazy. I just eat when I want to eat. Load only when used. This is lazy.

Dual detection Lock implementation:

1  PackageCom.roc.singlet;2 3 /**4 5 * Dual detection Lock Implementation6 7  * @authorLIAOWP8 9  *Ten  One  */ A  -  Public classSingletPatter3 { -  the  Public StaticSingletPatter3 instance =NULL; -  -   -  + //each mode sends synchronization content to the if interior, improving execution efficiency. Only the first time synchronization, the creation will not be necessary -  +  Public StaticSingletPatter3 getinstance () { A  at if(instance==NULL){ -  - SingletPatter3 SingletPatter3; -  - synchronized(SingletPatter3.class) { -  inSingletPatter3 =instance; -  to if(singletpatter3==NULL){ +  - synchronized(SingletPatter3.class) { the  * if(singletpatter3==NULL){ $ Panax NotoginsengSingletPatter3 =NewSingletPatter3 (); -  the } +  A } the  +Instance =SingletPatter3; -  $ } $  - } -  the } - Wuyi returninstance; the  - } Wu  -   About  $ PrivateSingletPatter3 () { -  -   -  A } +  the}

Problem: Due to compiler optimization reasons and JVM underlying internal model reasons. There are occasional problems.

How to implement a static inner class:

 PackageCom.roc.singlet;/*** Static Inner class implementation method *@authorLIAOWP **/ Public classSingletPatter4 {Private Static classsingletpatterinstance{Private StaticSingletPatter4 instance =NewSingletPatter4 ();}  Public StaticSingletPatter4 getinstance () {//use to call the internal class loading mode, that is, lazy loadingreturnsingletpatterinstance.instance;}  PublicSingletPatter4 () {}} Advantages: External no static decoration, not immediately loaded. The instance is the final static type, which guarantees that there is only one instance in memory. Thread safety. The benefits of concurrent, efficient calls and lazy loading. Enumeration Implementation Method PackageCom.roc.singlet;/*** Enumeration method to implement a single case *@authorLIAOWP **/ Public enumSingletPatter5 {INSTANCE; }  

How to choose:

The singleton object, which takes up less resources and does not need to delay loading, can choose the enumeration and the A hungry man-type.

enumerated type "A Hungry Man".

A singleton object takes up a lot of resources. Delay Loading: Static inner class lazy type

static inner class "lazy-style"

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.