Introduction to Java design patterns and detailed explanation of eight common design patterns

1、 What is a design pattern

Design pattern (design pattern) is a set of code design experience that is repeatedly used, known by most people, classified and catalogued. The purpose of using design patterns is to reuse code, make code easier to be understood by others and ensure code reliability. There is no doubt that design patterns win more for themselves, others and the system. Design patterns make code preparation truly engineering and design Pattern is the cornerstone of software engineering, just like a brick of a building. The rational use of design patterns in the project can perfectly solve many problems. Each pattern has corresponding principles to correspond to it. Each pattern describes a recurring problem around us and the core solution of the problem, which is also the reason why it can be widely used. Simply put:

Pattern: a general solution to a certain kind of problem in some scenarios.

Scenario: environment of the project

Problems: constraints, project objectives, etc

Solution: universal and reusable design to solve constraints and achieve goals.

2、 Six principles of design pattern

Because the design pattern is based on the implementation of these principles, it is necessary to understand these principles. The following is a brief introduction to several principles of object-oriented programming.

1. Open close principle

The opening and closing principle means that it is open to extensions and closed to modifications. When the program needs to be expanded, you can't modify the original code to achieve a hot plug effect. So in a word, in order to make the program extensible, easy to maintain and upgrade. To achieve this effect, we need to use interfaces and abstract classes, which will be mentioned in the following specific design.

2. Liskov Substitution Principle

Liskov Substitution Principle (LSP) is one of the basic principles of object-oriented design. Richter's substitution principle says that where any base class can appear, subclasses must appear. LSP is the cornerstone of inheritance reuse. Only when the derived class can replace the base class and the function of the software unit is not affected, the base class can be truly reused, and the derived class can also add new behavior on the basis of the base class. Richter's substitution principle is a supplement to the "open close" principle. The key step in realizing the "open close" principle is abstraction. The inheritance relationship between base class and subclass is the concrete implementation of abstraction, so the Richter substitution principle is the specification of the specific steps to realize abstraction.

3. Dependency Inversion Principle

This is the basis of the opening and closing principle. The specific content: true interface programming depends on abstraction rather than concrete.

4. Interface aggregation principle

This principle means that using multiple isolated interfaces is better than using a single interface. It also means to reduce the coupling between classes. From here, we can see that in fact, the design pattern is a software design idea, starting from the large-scale software architecture for the convenience of upgrading and maintenance. So it appears many times above: reduce dependence and reduce coupling.

5. Demeter principle

Why is it called the least known principle, that is, an entity should interact with other entities as little as possible to make the system functional modules relatively independent.

6. Composite Reuse Principle

The principle is to try to use composition / aggregation instead of inheritance.

3、 Three categories of design patterns

Creation mode: the mode of object instantiation. Creation mode is used to decouple the instantiation process of objects.

Structural pattern: combine classes or objects to form a larger structure.

Behavioral patterns: how classes and objects interact, and divide responsibilities and algorithms.

As shown in the figure below:

4、 Key points of patterns in each classification

Create pattern

Singleton mode: a class can only have one instance, providing a global access point.

Simple factory: a factory class determines which product class instance to create according to the passed in parameters.

Factory method: define an interface for creating objects, and let subclasses decide which class to instantiate.

Abstract factory: create families of related or dependent objects without explicitly specifying specific classes.

Builder pattern: encapsulates the construction process of a complex object and can be constructed step by step.

Prototype pattern: create a new instance by copying an existing instance.

Structural model

Adapter pattern: convert the method interface of a class into another interface desired by the customer.

Combination mode: combine objects into a tree structure to represent the hierarchy of "" part whole "".

Decoration mode: dynamically add new functions to objects.

Proxy mode: provide a proxy for other objects to control the access of this object.

Hengyuan (fly quantity) mode: effectively support a large number of fine-grained objects through sharing technology.

Appearance mode: provide a unified method to access a group of interfaces in the subsystem.

Bridging pattern: separate the abstract part from its implementation part so that they can change independently.

Behavioral model

Template pattern: define an algorithm structure and delay some steps to subclass implementation.

Interpreter pattern: given a language, define a representation of its grammar, and define an interpreter.

Policy pattern: define a series of algorithms, encapsulate them, and make them interchangeable.

State mode: allows an object to change its behavior when its internal state changes.

Observer pattern: one to many dependencies between objects.

Memo mode: keep the internal state of the object without destroying the encapsulation.

Mediator pattern: a mediation object is used to encapsulate a series of object interactions.

Command mode: encapsulate the command request as an object, so that it can be parameterized with different requests.

Visitor mode: add new functions to a group of object elements without changing the data structure.

Responsibility chain mode: decouple the sender and receiver of the request, so that multiple objects have the opportunity to process the request.

Iterator pattern: a method of traversing and accessing individual elements in an aggregate object without exposing the internal structure of the object.

5、 Detailed explanation of eight common design modes

1. Single instance mode

The so-called singleton design means that only one instantiated object is allowed for a class. The best understood design pattern is divided into lazy and hungry.

1.1 hungry Han style

-- the construction method is privatized, and no new instantiated object can be generated externally. The instantiated object can only be obtained through the static method

1.2. Lazy type

-- the operation of instantiating a singleton object is generated only when the singleton object is used for the first time

When multiple threads execute the getInstance method concurrently, the lazy type will have thread safety problems, so synchronized is used to synchronize threads. When a thread obtains a lock, other threads can only wait outside for its execution to complete. The hungry Chinese style has no thread safety problem.

2. Factory design mode

Factory patterns are divided into factory method patterns and abstract factory patterns.

Factory method model

2.1 ordinary factory mode

Establish a factory class to create instances of some classes that implement the same interface.

2.2. Multiple plant method mode

This mode is an improvement on the ordinary factory method mode. In the ordinary factory method mode, if the string passed is wrong, the object cannot be created correctly, while multiple factory method modes provide multiple factory methods to create objects respectively.

2.3. Static factory method mode

Set the methods in the above multiple factory method patterns as static. You can call them directly without creating an instance.

2.4 abstract factory mode

A problem with the factory method pattern is that the creation of a class depends on the factory class, that is, if you want to extend the program, you must modify the factory class, which violates the closure principle. Therefore, from the design point of view, there are certain problems. How to solve them? Then, the abstract factory pattern is used to create multiple factory classes. In this way, once new functions need to be added, new factory classes can be added directly without modifying the previous code.

3. Builder mode

The factory class pattern provides the pattern of creating a single class, while the builder pattern centralizes and manages various products to create composite objects. The so-called composite object means that a class has different properties.

4. Adapter design mode

Adapter pattern is to convert the interface of a class into another interface representation expected by the client. The purpose is to eliminate the class compatibility problem caused by interface mismatch.

It is mainly divided into three categories: class adapter mode, object adapter mode and interface adapter mode.

4.1 adapter mode of class:

4.2 adapter mode of object

The basic idea is the same as the adapter mode of the class, except that the adapter class is modified. This time, it does not inherit the source class, but holds an instance of the source class to solve the compatibility problem.

4.3 adapter mode of interface

The interface adapter is like this: sometimes there are multiple abstract methods in an interface we write. When we write the implementation class of the interface, we must implement all the methods of the interface, which is obviously wasteful sometimes, because not all the methods are needed, and sometimes only some are needed. To solve this problem, We have introduced the adapter pattern of the interface. With the help of an abstract class, the abstract class implements the interface and implements all methods. However, we do not deal with the original interface and only contact the abstract class. Therefore, we write a class, inherit the abstract class and rewrite the methods we need.

As the name suggests, decoration mode is to add some new functions to an object, which is dynamic. It requires that the decoration object and the decorated object implement the same interface, and the decoration object holds the instance of the decorated object.

6. Strategy mode

The policy pattern defines a series of algorithms and encapsulates each algorithm so that they can replace each other, and the change of the algorithm will not affect the customers using the algorithm. An interface needs to be designed to provide a unified method for a series of implementation classes, and multiple implementation classes implement the interface, An abstract class (optional, belonging to the auxiliary class) is designed to provide auxiliary functions. The decision of the policy mode lies with the user. The system itself provides the implementation of different algorithms, adds or deletes algorithms, and encapsulates various algorithms. Therefore, the policy mode is mostly used in the algorithm decision-making system, and external users only need to decide which algorithm to use.

7. Agent mode

Proxy mode refers to providing a proxy object to an object, and the proxy object controls the reference to the original object. Agents can be divided into static agents and dynamic agents. Through the proxy mode, you can use the proxy object to add additional functions to the proxy object, so as to expand the functions of the proxy object. It can be used to calculate the execution time of a method and record logs before and after the execution of a method.

7.1 static agent

Static proxy requires us to write out the proxy class and the proxy class, and a proxy class corresponds to a proxy class one by one. The proxy class and the proxy class need to implement the same interface. Through aggregation, the proxy object has a reference to the proxy object, so as to realize the purpose of the proxy object controlling the proxy object.

7.2 dynamic agent

After JDK 1.3, Java passed Java Three classes in lang.reflect package are proxy, invocationhandler and method to support dynamic proxy. Dynamic proxy is often used to have several proxy objects, and the functions added to each proxy object are the same (for example, log before and after each method runs). The proxy class of dynamic proxy does not need to be written by us. Java automatically generates the proxy class source code, compiles it, and finally generates the proxy object.

Steps to create a dynamic proxy object: 1) specify a series of interfaces to create a proxy object; 2) create an invocationhandler object; 3) specify this proxy as a proxy object of some other object; 4) call the invoke of the processor () method adopts proxy. On the one hand, it passes the call to the real object, and on the other hand, it performs various required operations

8. Template method mode

Requirements: a brief description: the company has procedures, testing, HR, project managers, etc. the following uses the template method mode to record the work situation of all personnel

There are three types of roles in the template method pattern:

1. Concrete method

2. Abstract method

3. Hook method

Final test:

View the work of all personnel:

Check when the program left the company:

reference resources:

   https://www.cnblogs.com/pony1223/p/7608955.html

   https://blog.csdn.net/gfuugff/article/details/86641373?utm_medium=distribute.pc_relevant.none -task-blog-BlogCommendFromMachineLearnPai2-4. channel_ param&depth_ 1-utm_ source=distribute. pc_ relevant. none-task-blog-BlogCommendFromMachineLearnPai2-4. channel_ param

   https://www.cnblogs.com/Diyo/p/11415588.html

   https://blog.csdn.net/wmq880204/article/details/75106848

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>