Summarize the main points of use and Java implementation of 24 common design patterns

Source: Internet
Author: User
Tags generator static class volatile

Design patterns are specific solution patterns (routines) that can be reused for specific problems in a specific situation that is constantly emerging. According to the three categories of creation, structure and behavior, this paper summarizes the main points of use of 24 kinds of design patterns, including applicable scenarios, solutions, and their corresponding Java implementations.

1 overview

1.1 Concepts

Design patterns are some sort of "solution" to a "problem" in an ever-present "context" scenario:

    • "Problem" must be repeated, "solution" must be reusable;

    • "Problem" contains "a goal" and "a set of constraints", when the solution in the balance between the two is a useful model;

    • The design pattern is not the legal norm, but the guideline, the actual use can be fine-tuned as needed, just to make good comments so that others know;

    • Many of the seemingly new models are essentially variants of existing models;

    • Pattern Selection principle: Try to design in the simplest way possible, unless you are using design patterns in order to adapt to possible future changes, because design patterns introduce more complex relationships and do not use patterns in order to use patterns.

1.2 Six major principles

The six principles of the English first letter together is solid (stable), so also known as the solid principle.

1.2.1 Single Duty principle (Responsibility Principle)

There should never is more than one reason for a class-to-change.
A class has only one responsibility, and not multiple responsibilities are coupled in a class (for example, interfaces and logic are separated).

1.2.2 Open Closure principle (opening Closed Principle)

Software entities like classes, modules and functions should is open for extension but closed for modifications.
Open for extensions, close for modifications, use interfaces and abstract classes.

1.2.3 Richter Replacement principle (Liskov Substitution Principle)

Functions that use pointers or references to base classes must is able to use objects of derived classes without knowing I T.
To ensure that the parent class can appear, subclasses must be able to appear, which is the cornerstone of inheritance reuse.

1.2.4 Least know the principle (Least knowledge Principle)

Immediate friends.
Low dependence, the entities are as independent as possible and minimize interaction.

1.2.5 Interface Isolation principle (Interface segregation Principle)

The dependency of one class to another one should depend on the smallest possible interface.
The customer (client) should not rely on methods that it does not use. Try to use multiple interfaces for compositing, rather than a single interface to couple multiple functions.

1.2.6 Dependency Inversion principle (Dependency inversion Principle)

The modules should not depends upon low level modules.
Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.
To rely on abstractions (interfaces or abstract classes), rather than concrete (concrete classes).

1.3 Value

Design patterns are 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.
Design patterns seem to complicate the simple problem. But "simple" design flexibility is poor, in the current project is not easy to expand, get other projects are not used, equivalent to "one-time code." The design pattern code, the structure is clear, the current project is easy to expand, to get other projects also applicable, is a universal design.
Many programmers come into contact with the design pattern, all have the feeling of brief encounter, feel themselves reborn, reached the new realm, the design pattern can be used as the standard of the programmer division level.
But we can not get caught in the trap of patterns, in order to use patterns to go to the pattern, that will fall into the formalism.

1.4 Selection Method

    • Each design pattern implies several OO principles, which can be returned to the OO principle when there is no suitable design mode to choose.

    • The best way to use patterns: there are various patterns in the mind, to see if there is a design or code, where you can use these patterns to reuse experience;

    • The power of shared design pattern vocabularies (including verbal terminology, naming of classes and methods in code):
      (1) When communicating with others, referring to the name of the design pattern implies its pattern;
      (2) using the model to observe the software system can be maintained at the design level, and will not be stuck in trivial object details;
      (3) Communication between teams with design patterns is not easily misunderstood.

1.5 Important books

Author: Erich Gamma (Erich gamma), Richard Helm, Ralph Johnson,john Vlissides, later known as "Gang of Four" (Gang of Four,gof). There are two books:

1.5.1 "Head First design mode"

It is highly recommended to read. The English title is "Head first Design Patterns".
People who believe in Jesus have to read the Bible, and people who believe in Oo (object oriented) read the "head first design mode" of the four-person group, the official website head first, Patterns. 2004 The book won the Jolt Award (similar to the Academy Award in the field of film).

    • Is the first to classify the pattern of the hero, opened the software field of a great leap forward;

    • Templates for patterns: include names, classes, intentions, motivations, applicability, class diagrams, participants and their collaborations, results, implementations, sample code, known applications, related patterns, and so on.

1.5.2 "design pattern: The basis of reusable object-oriented software"

The English title is the Design patterns:elements of reusable object-oriented software. is also the four-person group.
Software Engineering in the field of software design of a book, proposed and summed up some common software design problems of the standard solution, called the Software design mode. The book was first published on October 21, 1994 and has been printed in 40 brushes by March 2012.

2 Classification and definition

Design patterns can be divided into three large categories, each of which contains several specific patterns.
Easy to confuse several modes: Simple factory S/abstract factory A/factory method F/Template Method T

    • "Factory": The band is only used to create instances, such as s/a/f, not with the unlimited, such as T;

    • The word "method": the band without additional client involvement, can operate independently, such as f/t, without the need for additional client calls, such as s/a.

2.1 Creation type (creational Patterns)

Used to create objects, put the work of creating objects in another object, or defer them to subclasses.

2.1.1 Single case (Singleton)

Ensure that a class has only one instance and provides a global access point.
It is important to note that the use of singleton under multiple ClassLoader causes a singleton instance to be available under all types of loaders, because each classloader has its own separate namespace.
A single case in the JDK has Runtime.getRuntime() , NumberFormat.getInstance()
The following summarizes four thread-safe implementations of Java. Each implementation can be Singleton.getInstance().method(); invoked.

2.1.1.1 A Hungry man way

Key idea: As a static global variable for a class, the class is instantiated when it is loaded.
The disadvantage is that you have instantiated and wasted resources before actually using the instance (and potentially useless).
For a Hotspot VM, if the class is not involved, it is actually instantiated the first time that getinstance () is called.

/** * @author: Kefeng.wang * @date: 2016-06-07 10:21 **/public class Singleton {    private static Singleton instance = N EW Singleton ();    Private Singleton () {    }    //Based on classLoader mechanism, automatically achieves the effect of thread safety public    static Singleton getinstance () {        return instance;    }    public void Method () {        System.out.println ("Method () ok.");}    }

2.1.1.2 Lazy Way

Key idea: Synchronization is implemented on Method getinstance ().
The disadvantage is that each call to getinstance () will be locked, but in fact only the first instance of the need, the subsequent locking are wasted, resulting in a large performance drop.

/** * @author: Kefeng.wang * @date: 2016-06-07 10:21 **/public class Singleton {    private static Singleton instance = null;    Private Singleton () {    } public    static synchronized Singleton getinstance () {        if (instance = = null) {            Instance = new Singleton ();        }        return instance;    }    public void Method () {        System.out.println ("Method () ok.");}    }

2.1.1.3 Lazy Way (double check plus lock)

Key idea: The case is not synchronized when the check is not yet created, and then the synchronization check is not instantiated until the instantiation. To significantly reduce the synchronization situation.
The disadvantage is that jdk5+ is required, otherwise the implementation of volatile by many JVMs causes double lock invalidation. But now very few developers will use JDK5, so this shortcoming is not very related.

/** * @author: Kefeng.wang * @date: 2016-06-07 10:21 **/public class Singleton {    private volatile static Singleton ins tance = null; Note Volatile    private Singleton () {    } public    static Singleton getinstance () {        if (instance = = NULL) {// Preliminary check:            synchronized (singleton.class) {/////re-sync (to Singleton.class)                if (instance = = NULL) {//ACK not yet instantiated                    ins tance = new Singleton ();}}        }        return instance;    }    public void Method () {        System.out.println ("Method () ok.");}    }

2.1.1.4 internal static class mode (recommended!) )

Key idea: A global static member is placed in an inner class and instantiated only if the inner class is referenced for the purpose of deferred instantiation. It's a perfect solution:

    • Ensure deferred instantiation to getinstance () calls;

    • No need to lock, good performance;

    • Not subject to JDK version limitations.

/** * @author: Kefeng.wang * @date: 2016-06-07 10:21 **/public class Singleton {    private static class Instanceholder { Lazy Load Instance        private static Singleton instance = new Singleton ();    }    Private Singleton () {    } public    static Singleton getinstance () {        return instanceholder.instance;    }    public void Method () {        System.out.println ("Method () ok.");}    }

2.1.2 Generator (builder)

Encapsulates the creation of an object into a generator object, which is called by the customer to complete the creation of the procedure.
Java Implementation Please refer to StringBuilder the source code, here gives its use effect:

StringBuilder sb = new StringBuilder (); Sb.append ("Hello world!"). Append (123). Append ('! '); System.out.println (Sb.tostring ());

2.1.3 Simple Factory (easy Factory) ★

The

is not a true "design pattern." itself is the factory implementation class, directly provides the creation method (can be multiple), can be a static method. There are boolean.valueof (string) , class.forname (String) in the JDK.

/** * @author: Kefeng.wang * @date: 2016-06-09 19:42 **/public class Dpc3_simplefactorypattern {private static Class S                implefactory {public commonproduct createproduct (int type) {//factory method, return "Product" interface, parameter can be no if (type = = 1) { return new Commonproductimpla ();            Product Specific Class} else if (type = = 2) {return new COMMONPRODUCTIMPLB ();            } else if (type = = 3) {return new COMMONPRODUCTIMPLC ();            } else {return null;        }}} private static class Simplefactoryclient {private simplefactory factory = null;        Public simplefactoryclient (Simplefactory factory) {this.factory = factory;            Public final void Run () {commonproduct CommonProduct1 = factory.createproduct (1);            Commonproduct commonProduct2 = factory.createproduct (2);            Commonproduct commonProduct3 = factory.createproduct (3); System.out.println (CommonProduct1 + "," + CommonProduct2 + "," + commonProduct3); }} public static void Main (string[] args) {Simplefactory factory = new Simplefactory ();//Factory Instance New Simplefactoryclient (Factory). Run (); Incoming client Class}}

2.1.4 Abstraction Factory (abstract Factory) ★

An abstract class that defines an abstract method for creating an object. After inheriting multiple implementation classes, implement the method of creating the object.
The client flexibly chooses the implementation class to complete the creation of the object.
This pattern is used in the JDK NumberFormat.getInstance() .

2.1.5 Factory Methods (Factory method) ★

The Division of the creation method for abstract classes and implementation classes is similar to the abstract factory.
The difference is: This mode does not need the client, its own method can be done before and after the object creation operations.

2.1.6 Prototype (Prototype)

When the process of creating an instance is complex or expensive, it can be implemented by cloning. Like in Java Object.clone() .

2.2 Structural type (Structural Patterns)

A composite relationship for a class or object.

2.2.1 Adapter (Adapter)

Adapting an interface to another desired interface eliminates compatibility issues caused by mismatched interfaces.
For example Enumeration<E> , to fit into, to fit Iterator<E> Arrays.asList() T[] into List<T> .

2.2.2 Bridging (BRIDGE) ★

Things are composed of multiple factors, and each factor has an abstract class and multiple implementation classes, which can eventually be freely combined.
For example, a variety of remote CONTROL + TV, a variety of models + multiple traffic + drivers. The and in the JDK JDBC AWT .

2.2.3 Combination (Composite) ★

Organizes the "part/whole" of an object in a tree-shaped structure to treat a single object or multiple object combinations uniformly.
such as multi-level menu, binary tree and so on.

2.2.4 Decoration (Decorator)

The runtime dynamically attaches responsibilities to the adorner.
There are two ways to extend functionality, class inheritance is a compile-time static decision, and decorator mode is a runtime dynamic decision with a unique advantage.
StringReaderFor example LineNumberReader , after being decorated, the associated interface is extended for the character stream line .

2.2.5 appearance (facade) ★

Provides a unified high-level interface to access a group of interfaces in the subsystem, making the subsystem easier to use.
For example, the startup (or shutdown) of a computer is called the cpu/memory/disk's respective start (or shutdown) interface.

2.2.6/Fly Volume (Flyweight)

Use shared technology to effectively support a large number of fine-grained objects.
A text processor, for example, does not need to generate multiple glyph objects for multiple occurrences of each character, but rather to share a Glyph object with multiple occurrences of the same character in an external data structure.
Integer.valueOf(int)This pattern is used in the JDK.

2.2.7 Agent (proxy)

Proxy creates and holds a reference to subject, and the proxy is forwarded to subject when the client calls proxy.
such as the Collections collection view in Java, RMI/RPC Remote call, cache proxy, firewall proxy and so on.

2.3 Behavioral type (behavioral Patterns)

The invocation relationship used for a class or object.

2.3.1 Chain of responsibility (Chain of responsibility)

A request is passed along a chain until a handler on the chain processes it.
such as the filter in SPRINGMVC.

2.3.2 Command

Encapsulates a command as an object, optionally storing/loading, passing, executing/undoing, queueing, logging, and so on, decoupling the "requestor of the action" from "Performer of action".
The participants include the Invoker (caller) and command (commands) = Receiver (executor).
such as timed tasks, thread tasks Runnable .

2.3.3 Interpreter mode (interpreter)

Used to create a simple language interpreter that can handle scripting languages and programming languages, creating a class for each rule.
For example, in the JDK java.util.Pattern java.text.Format .

2.3.4 iterators (Iterator)

Provides a way to sequentially access individual elements of an aggregated object without exposing its internal behavior.
such as the and in the JDK java.util.Iterator java.util.Enumeration .

2.3.5 Mediator (mediator)

Encapsulates a series of object interactions using a mediation object that allows objects to be loosely coupled without explicitly referencing each other, and can independently change the interaction between them.
such as the and in the JDK java.util.Timer java.util.concurrent.ExecutorService.submit() .

2.3.6 Memorandum (Memento)

A Memo object is used to store a snapshot of the internal state of another object, which can be stored externally and then restored to its original state. such as Java serialization.
such as the and in the JDK java.util.Date java.io.Serializable .

2.3.7 Observer (Observer)

A one-to-many dependency between objects, the observer receives notification when the observer state changes.
The participants include Observable (the observed)/OBSERVER (Observer).
such as the events in RMI, java.util.EventListener .

2.3.8 Status (state)

When an object's internal state changes, its behavior changes as well. Its internal implementation is to define a state parent class that extends the state subclass for each state, and when the internal state of the object changes, the selected state subclass also switches, but the external only needs to interact with the object without knowing the existence of the State subclass.
such as the stop/play/pause status of the video player.

2.3.9 Strategy (strategy)

Define a set of algorithms that are encapsulated separately from the customer and do not affect customer use when the algorithm changes.
For example, different characters in the game, can use a variety of equipment, these equipment can be packaged in a strategic way.
Like in the JDK java.util.Comparator#compare() .

2.3.10 Template Method ★

Abstract classes define top-level logical frameworks (called "Template Methods"), and some steps (which can create instances or other operations) are deferred to the subclass implementation, which can run independently.
When a subclass implements the operation of creating an instance, the template method becomes the factory method pattern, so the factory method is a special template method.

2.3.11 Visitor (Visitor) ★

Without modifying the data structure of the visitor, the access operation is encapsulated in the visitor, and the key point is the interface provided by the visitor.
The application scenario is that the visitor is stable but the visitor is flexible, or the visitor has a variety of different operations.

2.4 Composite Mode (Compound)

Combine two or more patterns to form a solution to solve frequently occurring general problems.
Use case: MVC pattern (Model/view/controller), using patterns such as observer (OBSERVER), strategy (strategy), composition (Composite), Factory (Factory), Adorner (Decorator).
Use case: Home appliance = interface + data + logic control, Mall = storefront + warehouse + logic control.

3 Reference Documents

Wikipedia: Design Patterns
Wikipedia:software design Pattern
Tutorialspoint:design Pattern

Design patterns are specific solution patterns (routines) that can be reused for specific problems in a specific situation that is constantly emerging. According to the three categories of creation, structure and behavior, this paper summarizes the main points of use of 24 kinds of design patterns, including applicable scenarios, solutions, and their corresponding Java implementations.
Related articles:

Java Common Design Patterns detailed-Factory mode

Detailed memo mode and its implementation in Java design pattern programming

Related Article

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.