Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed introduction of 24 Design patterns of Java

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "detailed introduction of 24 design patterns of Java". In daily operation, I believe many people have doubts about the detailed introduction of 24 design patterns of Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "detailed introduction of 24 design patterns of Java". Next, please follow the editor to study!

Design pattern principle

Many excellent articles and books are very clear, I talk about my own experience. 1. The principle of single responsibility is that a class is responsible for only one thing. In this way, we can achieve the effect of decoupling, make the code look refreshing, and reflect the encapsulation of java. There is also a principle called Dimitt's rule, which is that one object knows as little as possible about another object and is also talking about decoupling. two。 The Richter substitution principle and the dependence-leading principle are talking about inheritance. The subclass can do whatever the parent class can do, and the subclass can rely on the parent class to do things as much as possible; but conversely, the parent class cannot rely on the subclass to do something. It embodies the inheritance characteristic of java. 3. The principle of interface isolation, interfaces should also be isolated as much as possible. In fact, the class is written too much, indeed the coupling is low, in order for them to communicate, the interface is the most used, after all, only need to know what to do, how to do, to visit that specific class. 4. The principle of opening and closing shall be closed to revision and open to expansion. That is, the code needs to be malleable and can not be destroyed to the original code structure.

Creator model

The creator pattern is designed to create the classes we use in an elegant way.

1. Simple factory model

This is less used, that is, there is a factory that tells you what I want, and you can build it for me when you have it. For example:

two。 Factory model

This is actually not much different from the simple factory model, which is to continue to split the factory. For example, just now EasyBallFactory is a main factory, and we are now split into SoccerFactory and BasketBallFactory to produce football and basketball respectively. A factory can produce different products according to the demand, for example, soccer can produce different sizes.

3. Abstract factory pattern

Abstract factory pattern mainly designs the concept of product group, which is a series of products produced by a factory. For example, while producing football, SoccerFactory can also produce matching football magazines.

4. Singleton mode

There are many forms of singleton pattern, and good practice should be double judgment to ensure that only one new comes out. Singletons can be said to be a very common design pattern. Singleton means that there can be only one in the lifecycle of a service container. For example, Servlet, Bean injected into Spring, and so on are all singletons.

5. Builder model

Create a complex object distribution. If a very large class has a lot of attributes, we can classify the attributes into a slightly smaller class, and then move several smaller classes together. A computer, for example, can be divided into slightly smaller parts, CPU, motherboard, and monitor. CPU, motherboard and monitor have more components and are no longer subdivided.

SpringBoot implements zero configuration, almost all configurations are written into java code, and a large number of configurations have to make the configuration class in builder mode, so the level is clear.

6. Prototype model

The prototype pattern is less used and is used to create duplicate objects. If you need to implement Cloneable, you can choose to override the clone () method. Clone can be divided into shallow cloning and deep cloning. Shallow cloning is just a clone reference, and the object is still one. Deep cloning is also a new object created, as follows:

Structural model

The above design pattern can help us to create objects very elegantly. Let's take a look at the models between several object relationships.

7. Agent mode

Spring AOP is a dynamic agent, what is dynamic do not look, have used Spring friends know it. Simply take a look at the most basic agent model. An agent is an object that assists another object to do something, and at the same time adds a little auxiliary function. For example, when you buy a car, you do spend money to buy it, but you can't talk to the manufacturer directly. You should buy it through 4S store, and at the same time, 4S store helps you get insurance deduction and other operations, and finally you get the car you want.

8. Adapter mode

Adapters, as the name implies, allow two incompatible things to work together. For example, the power supply of the socket is 220V, and the cell phone directly gives him 220V 50HZ AC power. I believe it will generally explode directly (except Nokia.) The mobile phone charger is adapted to reduce the voltage and turn alternating current into direct current. In addition to this operation that requires property changes (rather than examples), adapters are also used in terms of interface inheritance. Suppose a * * interface has a lot of methods to implement the class implementation, and I just write a new class that I just want to choose to implement one or two interfaces, then do I need to implement all the other methods, even if it is an empty implementation (simple implementation, without any logical operation), this is that we need an adapter class, empty implementation of those methods, my new class only needs to inherit this adapter class If you want to implement a method, you just need to override the corresponding method in the configuration class. This mode is basically used, after all, whose code does not have a * interface.

9. Bridging mode

Is the decoupling for abstraction and implementation. Decoupling again, it seems that the design pattern is to teach us how to decouple elegantly. The expansibility of the code is improved, and the dynamic switching of the code can be realized. The original Ball, Soccer, and BasketBall are then used to add new classes.

10. Decoration mode

A decoration class that adds a little function to the original class. Whether it is very similar to the agent mode or not, it makes sense that I can even move the whole code here. The meaning of the two modes is a little different. The agent mode is that the original object cannot do that, so it must be done by the agent object, and the dominant focus is on the agent object, such as buying a car. The decoration mode means that the original object is allowed to do this directly, but the function is enhanced a little, and the dominant thing lies in the original object. For example, sprinkle some salt when cooking.

11. Appearance mode

Also known as facade mode, is a facade, an operation does not need to let the object know the complexity of its internal implementation, as far as possible to let users feel is very simple. This is why we controller layer as much as possible (or certainly) less business logic, let the controller layer just play a function of passing parameters and universal parameter verification, and leave the rest to service. We also need to constantly encapsulate "long" code in our code into a method to "make it look good everywhere." Take a look at the code we have written, it only plays the role of passing parameters, and the client does not have to worry about how the football was created.

twelve。 Combination mode

The composition pattern is to organize the data that contains some kind of relationship together, a typical example is the tree structure. For example, the menu function, a menu in addition to its own attributes, may also contain submenus, you can use recursive methods when creating.

13. Sharing meta-mode

The sharing meta-pattern allows users to reuse existing objects as much as possible, so as to avoid the waste of resources to create objects repeatedly. First of all, you will think of database connection pooling and String constant pooling. By extension, almost all code related to caching will use the shared meta mode somewhat. The shared meta-pattern requires that most objects can be externalized. Here, we would like to talk about two concepts. The attributes of the sharing meta-mode object can be divided into two parts, the internal state and the external state. The internal state refers to the value that will not change with the environment, such as personal information, and the external state refers to the value that changes with the environment. Information that cannot be shared, such as a course taken by a college student.

Behavioral model

Once the objects are created and there is a structural relationship between the objects, it's time to see how they interact more elegantly.

14. Strategy mode

Define a set of algorithms, encapsulate each algorithm, and make them interchangeable. It can be said that it is the encapsulation of a group of algorithms, which carries out different operations according to the different requirements given by the client. For example, the following simple calculator.

15. Observer mode

An one-to-many dependency is defined, and when the state of an object (the observed) changes, all observers who depend on that object are notified to perform relevant operations. Many middleware rely on the observer pattern, such as RabbitMQ, and those event-driven models (as if node is). For example, the person being observed is the invigilator, and when the exam time is over, all the observer students are informed to hand in their papers.

16. Responsibility chain model

The chain of responsibility pattern creates a chain of receiver objects for the request, decoupling the sender and receiver. The filter chain is the responsibility chain model.

17. Template mode

An abstract class exposes a way / template that defines the method in which it is executed. Its subclasses can override the method implementation as needed, but the invocation will be made in the manner defined in the abstract class. SpringBoot encapsulates a lot of inheritance code for users, using templates, such as that pile of XXXtemplate.

18. State mode

To put it simply, it means that an object has different states and may behave differently depending on the state.

19. Iterator mode

Provides a method to access the elements within an object sequentially without knowing the internal structure. Nowadays, it is rare to implement iterators on your own, and basically mature frameworks or powerful JDK will give access methods, such as iterator in java. The main purpose of this is to further encapsulate the internal structure of the object, making the behavior and structure want to be coupled. Without giving an example, all the friends who have used iterator should know that they are constantly next to visit the next element.

20. Command mode

The command mode is to wrap the request in the object in the form of a command and pass it to the object. The calling object finds the appropriate object to deal with the command, and passes the command to the corresponding object, which executes. To put it simply, different requests are encapsulated into a single object, and different requests call different executors.

21. Memo mode

It is equivalent to taking a snapshot, recording a state of the object without destroying the structure of the object, which can be restored when appropriate. This is the way the database rolls back transactions. It is important to note that the object is not coupled to the memo itself, but to the memo management class (that is, List), which is easy to understand. after all, there is more than one snapshot.

twenty-two。 Visitor mode

When accessing a specific role, it needs to be accessed through the visitor. When an object is not convenient for you to access directly, you need to give your reference to the visitor and access the object through the visitor. For example, chemistry class, want to see a cell structure, because the naked eye can not directly see the things of the micro world, need to be accessed indirectly through a microscope.

23. Intermediary model

Reduce the complexity of communication between objects or things, reduce coupling. For example, in a distributed system, it is not an operation that requires real-time feedback, so we do not need to dock directly, we just need to tell the middleware what we want to do, and the middleware tells another system. For example, visit (user clicks) a news action, record who accessed what news, add 1 to the number of news views, and update user preferences in real time. In short, it is necessary to update n database tables and even manipulate multiple middleware data such as ES,Mongo. But for users, I just did a click operation, and the result I hope to get is to watch a piece of news, ah, you have so many operations, you are so slow, the user experience is very poor, and the concurrency is also very low, so it is better to make two small systems, system A, pull the news, push, and assemble a message and throw it to the MQ middleware, ok, the end, the user sees the news. Then system B listens, gets the news, and makes all kinds of updates. Here, this middleware is our intermediary. For example, the control layer in MVC is the intermediary between the presentation layer and the model layer. For example, the following chat room:

24. Interpreter mode

Construct a way of translation to translate a language or description into a language or description that we can easily understand. It is easy to understand here, which means that you can understand it and read it quickly. Originally, I also wanted to give some kind of high-end compiler to combine the underlying language and even the mechanical language with the high-level programming language we use. After thinking about it, in fact, Map can be regarded as a very good compiler, key you can store a very small string, value theoretically you can store anything, so the code will not be written.

At this point, the study of "detailed introduction of 24 design patterns of Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report