Wechat public account: Tangerine Java Technology pit article first gold mining platform, follow-up synchronization update public account, after attention reply “group” can join the Internet technology exchange & internal push group, and discuss interview problems with a group of big factory executives. Reply “666” to obtain all information packs available on the First-line Internet (including development software, development specifications, classic e-PDFs, and some premium learning courses).

preface

Recently, many students want me to sort out the content about design patterns. Today, I will briefly explain the core design patterns to master, their basic principles and application scenarios. Maybe the foundation is not solid enough to know not so complete, but also does not affect the code.

Personally think that the design pattern is just a methodology, theory for reference, so that you can better, more convenient support business, there is no need to spend too much time to write a variety of data demo otherwise, believe me, you will not believe it or not in the project.

To learn more about beautiful, efficient, and concise code writing, check out my homepage code Design Optimization column


7 principles of Design Patterns

Single responsibility: Only one responsibility (or method) per class

Interface isolation: Dependencies of one class on another should be based on the smallest interface. Dependency inversion: high-level modules should not depend on low-level modules, and both should depend on interfaces rather than details. Details depend on abstractions, programming towards interfaces

Substitution: Subclasses should be able to replace superclasses, and subclasses should try not to override superclass methods. Open closed principle: change to the provider, not to the consumer (i.e., code compatibility), use extensions to add functionality, not to change the original class

Demeter’s law: An object should have minimal knowledge of other objects (the least known principle)

Principle of composition reuse: when a class uses code (methods) from another class, try to use composition rather than inheritance


First, create type

1.1 Singleton mode

How it works: Ensure that there is only one instance of a class and provide a global point of access to that instance.

Hangry: Static constant static code block

LanHanShi

Synchronized (thread safe, low efficiency)

Judge and then synchronize (error writing)

Double judgment (IF-synchronization-IF)

Anonymous Static inner classes (simple, recommended)

Enumerations (simple, but slightly uncomfortable to write object methods in enumerations)

Example: java.lang.runtime #getRuntime(), java.awt.desktop #getDesktop()

1.2 Prototype Mode

How it works: Use an instance of a stereotype to specify the type of object to be created, and create new objects by copying the stereotype. Example: clone method of Java Object, Java. Util. Arrays. ArrayList# toArray ()

Shallow copy: Copies only the values of basic and string fields

Deep copy: Copy reference types (e.g., groups, objects) as well

Deep copy implementation: 1. Rewrite Clone, handle each reference object one by one (call the clone object), trouble, and if the relationship between objects is complex, one of the deep copy is not implemented, resulting in bug 2. Use serialization and deserialization, such as Json, or Java’s own serialization (binary)

1.3 Creator Mode (Generator Mode)

Principle:

Encapsulates the construction process of an object and allows step-by-step construction.

If object generation is too complex (lots of fields and assignments with dependencies that need to be called sequentially), you can encapsulate the assignment process as a build() and place it in a Builder class. This class provides an assignment method for each field and saves it until build() is called, which returns an instance of the object.

With this pattern, the caller doesn’t need to focus on the build process, just sets the value he or she wants, and then calls build() to get the object instance. And if the field is added or modified, the construction process changes, the caller is not aware, without modifying the code. Conforms to the open closed principle.

Example: StringBuilder, a ConfigurationBuilder for some frameworks, for building configurations.

1.4 Simple factory mode

How it works: Create an object without exposing the internal details to the client, and provide a common interface for creating the object. This pattern can avoid repeated code to determine which subclass to create when multiple callers create an object, and if there is one more subclass, the caller does not need to modify the code.

Example: Spring ApplicationContext’s getBean method.

1.5 Factory method pattern

How it works: an interface is defined to create an object, but it is up to the subclass to decide which class to instantiate. Factory methods defer instantiation to subclasses. This pattern solves the problem of changing the factory class every time a subclass is added to a simple factory. This pattern has problems. If a new subclass is added, a new subclass factory should be added at the same time, which makes the system more complex.

Examples: Calendar, NumberFormat

1.6 Abstract factory patterns

How it works: Provides an interface for creating related object families. As above, it is up to the subclass factory to decide which objects are created. This pattern is an updated version of factory methods, except that it creates multiple kinds of objects simultaneously (factory classes have multiple methods).

This pattern manages the creation of a new collection of a family of objects that are typically associated with each other and can be handled at creation time into a factory class. And for two subclass factories, it is generally possible to switch seamlessly, making it very convenient to change the code (that is, to change a subclass factory).

This pattern is cumbersome to add a member of an object family (that is, all factory classes need a new method), but simpler to add another class of object family (that is, a new subclass factory).


Two, structure

2.1 Adapter Mode

How it works: Convert an interface to an interface that another user needs. Define a class, implement the interface that the user needs, aggregate an interface object that needs to be transformed, call the methods of the aggregated object in the overridden method (the method that the user needs), and if the return value is required and the return value type is inconsistent, then go through the method and return it. This process is called adaptation. This class is called the adapter class. This mode is compatible with some old interfaces.

Example: java.util.arrays #asList() ADAPTS an array to a List, the Spring MVC HandlerAdapter

2.2 Decorator mode

Principle:

To dynamically add one or more functions (methods) to a class. The class that needs to be added is called A, and A class B is defined to implement the upper interface of A, and an instance object of A is aggregated. In the interface implemented by class B, methods of the aggregated object are directly called to other methods that do not care about. The method you care about can be fed before and after the call (for example, if a method returns a number, you can multiply the original return value by 2). At the same time, class B can add some other methods, which are the extra functions. Class B is the decorator class and class A is the decorator class.

The advantage of this mode is that the decorator class can also be treated as the decorator class, and then a layer of decorator can be used indefinitely.

Example: Java IO stream

2.3 Proxy Mode

Principle:

Controls access to other objects (method level), putting some pre – or post-processing through proxy objects before and after injection into the target object’s methods. Aspect oriented programming.

Type:

Static proxy: Defines a proxy class that implements the upper interface of the target object, aggregates a target object, and adds pre – and post-processing when overwriting methods.

Dynamic proxy:

Use java.lang.reflect.Proxy#getProxyClass to enable dynamic proxy in Java

CGLIB dynamic proxy: just a class. The implementation principle is that the ASM framework dynamically generates the subclass bytecode of the target object class, and then generates the proxy object through reflection.

Example: Spring AOP

2.4 Bridge mode

Principle:

Separate the abstraction from the implementation so that they can vary independently. Bridging means that wherever you put a bridge, there are two sides of the bridge, and the two sides of the bridge can change, but the bridge is always the same. Here, the bridge represents an operation (such as running software on a phone) and the two sides represent two dimensions of an operation (such as phone and software). At the same time, the operation after the bridge can also be regarded as one dimension to bridge with another dimension (for example, the two dimensions of software and people running on the mobile phone can be bridged to form a 3-dimensional nested bridge).

Example: JDBC get connection, get connection is one dimension, database is one dimension, there are multiple databases, so this is a bridge pattern where one database dimension changes and the other dimension does not change.

2.5 Enjoy Yuan Mode

Principle:

Use a shared approach to support a large number of fine-grained objects that share part of their internal state. Such as common thread pool, constant pool and so on, making the object acquisition speed up.

Example: java.lang.integer #valueOf() Java.lang.boolean #valueOf()

2.6 Combination Mode

Principle:

Grouping objects into a tree structure to represent the whole/part hierarchy allows users to work with individual and composite objects in the same way. In general, a certain degree of similarity between the part and the whole is needed to abstract it. Abstract the part/whole to get a public abstract class or interface, and then implement the class according to the specific role to do different processing.

Example: java.util.map #putAll(Map), java.util.list #addAll(Collection) java.util.set #addAll(Collection)

2.7 Appearance Modes

Principle:

Provides a unified interface for accessing a set of interfaces in a subsystem, making the subsystem easier to use.


Three, behavior type

3.1 Chain of Responsibility (chain of Responsibility) mode

How it works: Multiple objects have a chance to process the request, chain them together, and send the request along the chain until one object processes it, thereby avoiding coupling between the sender and receiver of the request.

Example: javax.servlet.file #doFilter(), netty Handler Chain

3.2 Observer Mode

How it works: Define one-to-many dependencies between objects. When an object’s state changes, all of its dependencies are notified and automatically updated. A Subject is an object being observed, and all of its dependencies are called observers.

Examples: Swing event listener (button event, mouse event), JS event listener

3.3 Status Mode

How it works: Allow an object to change its behavior when its internal state changes, so that the object appears to change the class to which it belongs. The state mode is mainly used to solve the problem of state transition, when the state transition occurs, then the Context object changes its behavior.

3.4 Policy Mode

Principle: Define a set of algorithms, encapsulate each algorithm, and make them interchangeable. The policy pattern makes the algorithm independent of the clients that use it. The policy pattern is primarily used to encapsulate a family of algorithms that can be replaced with each other and dynamically replace the algorithms used by the Context as needed.

Example: java.util.Com parator# compare (), javax.mail. Servlet. HTTP. HttpServlet

3.5 Template Method Mode

Principle: Define an algorithm framework and defer implementation of some steps to subclasses. With the template approach, subclasses can redefine certain steps of the algorithm without changing the structure of the algorithm.

Example: the Java. Util. Collections# sort ()

3.6 Command Mode

How it works: Split each operation of an object (command receiver) into each command class, and use a command management class to manage those commands. The commands can be put into the queue to execute in order, and the operation log of the commands can be recorded in a unified manner, and the undo operation can be supported (each command can be implemented corresponding undo).

The advantage of this mode is that if the commands are abstracting into several standard commands (such as on and off), and then managing the operation of multiple command receivers (such as lights, TV sets, air conditioners), it is easy to add new command receivers, which is also called universal remote control with good expansibility.

3.7 Mediation Mode

Principle: Centralize complex communication and control patterns between related objects. Reduce the coupling between subsystems. Similar to a message receiving and receiving center, responsible for the word system message transfer, so that subsystems can carry on certain interaction.

Example: Thread pool manages threads and tasks to be executed.

3.8 Memorandum Mode

How it works: The internal state of an object is obtained without violating encapsulation, allowing the object to be restored to its original state if needed. For example, make a save for the current state of the game, and then read the state to restart after dying in a subsequent game.

3.9 Visitor Mode

How it works: Add new capabilities to an object structure, such as a composite structure. Using the visitor pattern allows for dynamic binding of overloads (that is, pseudo-double dispatch) with the same effect as using Instanceof in the overloaded method, but with the visitor pattern, the scalability is better.

3.10 The iterator pattern

How it works: Provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the aggregate object.

Example: the Java. Util. Iterator

3.11 Interpreter mode

How it works: An interpreter is created for a language, usually defined by the language’s syntax and parsing.

Examples: EL expressions, Freemaker templates

3.12 Empty Object mode

How it works: Use an empty object that does nothing to replace NULL, avoiding NULL object judgment and NULL pointer exceptions.


If you need information, you can reply to the public number [design Mode] keyword to obtain the complete PDF information

All right, it’s 12:00 p.m., so if that sounds good, pleasexdmRetweet attention under oh =. =

The last

  • Articles are original, original is not easy, thanks to the mining platform, feel fruitful, help three even ha, thank you
  • Wechat search public number: Orange pine Java technology nest, make a friend, enter the Internet technology exchange group
  • All the code, sequence diagram and architecture diagram involved in the article are shared and can be requested for free through the public number plus group
  • Article if there is a mistake, welcome to comment messages pointed out, also welcome to reprint, the trouble to mark the source is good