In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces what are the principles of design patterns in Java, the content is very detailed, interested friends can refer to, hope to be helpful to you.
one。 Principle of single responsibility
The single responsibility principle is the simplest object-oriented design principle, which is used to control the granularity of classes. The principle of single responsibility is defined as follows:
Single responsibility principle (Single Responsibility Principle, SRP): a class is responsible for only one corresponding responsibility in a functional area, or can be defined as: as far as a class is concerned, there should be only one reason for its change.
The principle of single responsibility tells us that a class should not be too "tired"! In a software system, the more responsibilities a class (from modules to methods) assumes, the less likely it is to be reused, and if a class assumes too many responsibilities, it is equivalent to coupling these responsibilities together. when one of the duties changes, it may affect the operation of other responsibilities, so it is necessary to separate these responsibilities and package different responsibilities in different classes. Different reasons for change are encapsulated in different classes, and if multiple responsibilities always change at the same time, they can be encapsulated in the same class.
The principle of single responsibility is the guiding principle to achieve high cohesion and low coupling. It is the simplest but most difficult principle to apply. It requires designers to discover and separate different responsibilities of classes. The multiple responsibilities of discovering classes require designers to have strong analysis and design ability and relevant practical experience.
Here is a simple example to further analyze the principle of single responsibility:
The developers of Sunny Software Company put forward the initial design scheme as shown in figure 1 for the graphical statistics module of customer information in a CRM (Customer Relationship Management) system.
Fig. 1 structure diagram of initial design scheme
In figure 1, the methods in the CustomerDataChart class are illustrated as follows: the getConnection () method is used to connect to the database, findCustomers () is used to query all customer information, createChart () is used to create charts, and displayChart () is used to display charts.
It is now reconstructed using the principle of single responsibility.
In figure 1, the CustomerDataChart class takes on too much responsibility, including both methods related to the database and methods related to chart generation and display. If you also need to connect to the database or use the findCustomers () method to query customer information in other classes, it is difficult to achieve code reuse. Whether it is to modify the database connection or to modify the way the chart is displayed, it needs to be modified, which is more than one reason for its change and violates the principle of single responsibility. Therefore, the class needs to be split to meet the principle of single responsibility, and the class CustomerDataChart can be split into the following three categories:
(1) DBUtil: responsible for connecting to the database, including database connection method getConnection ()
(2) CustomerDAO: responsible for operating the Customer table in the database, including adding, deleting, modifying and querying the Customer table, such as findCustomers ()
(3) CustomerDataChart: responsible for chart generation and display, including methods createChart () and displayChart ().
The structure reconstructed using the single responsibility principle is shown in figure 2:
Fig. 1 original structure diagram
After further analysis of the system, it is found that the process of sending mail is the same for both ordinary customers and VIP customers, that is to say, the code in the two send () methods is duplicated, and new types of customers will be added to the system. In order to make the system have better expansibility and reduce code duplication, the Richter substitution principle is used to reconstruct it.
In this example, you can consider adding a new abstract customer class Customer, and taking the CommonCustomer and VIPCustomer classes as its subclasses, and the mail sending class EmailSender class is programmed for the abstract customer class Customer. According to the Richter substitution principle, the place that can accept the base class object must be able to accept the subclass object, so change the parameter type of the send () method in EmailSender to Customer. If you need to add a new type of customer, just make it a subclass of the Customer class. The refactored structure is shown in figure 2:
Fig. 2 structure diagram after reconstruction
IV. Principle of reliance on inversion
Definition: high-level modules should not rely on lower-level modules, both should rely on their abstractions; abstractions should not rely on details; details should rely on abstractions. That is, programming for the interface, not for the implementation.
In fact, relying on reversal means that no one should rely on each other, except for the agreed interface, everyone can be flexible. Dependency inversion can be said to be the symbol of object-oriented design, it does not matter which language to write the program, if you consider how to program for the abstract rather than for the details, that is, all dependencies in the program are terminated in abstract classes or interfaces, that is, object-oriented design, otherwise it is procedural design. If the various parts or classes of the design depend on each other, it is highly coupled and difficult to maintain and expand, which does not reflect the benefits of object-oriented.
Rely on the inversion principle, for example, a team, with requirements group, development group, test group, development group and test group, all do their own corresponding work after facing the same requirements. It should not be that the test team makes test cases according to the requirements understood by the development team, that is to say, both the development team and the test team work directly towards the demand group. Everyone's goal is the same, to ensure that the product is launched on time. Requirements are independent of development and testing.
The principle of dependency inversion is based on the fact that abstract things are much more stable than the variability of details. An architecture based on abstraction is much more stable than an architecture based on details. In java, abstraction refers to interfaces or abstract classes, and details are concrete implementation classes. The purpose of using interfaces or abstract classes is to formulate specifications and contracts without involving any specific operations, leaving the task of showing details to their implementation classes to complete.
The central idea of dependency inversion principle is interface-oriented programming, there are three ways to transfer dependencies, the above is interface transfer, and there are two other ways: construction method transfer and setter method transmission. I believe that those who have used the Spring framework will be familiar with the dependency transfer mode.
In actual programming, we generally need to do the following three points:
Try to have abstract classes or interfaces, or both, for lower-level modules.
The declaration type of a variable is an abstract class or interface as far as possible.
Follow the Richter substitution principle when using inheritance.
In a word, the principle of dependency inversion requires us to program interface-oriented. If we understand interface-oriented programming, we will understand dependency inversion.
5. Interface isolation principle (Interface Segregation Principle)
The meaning of the principle of interface isolation is to establish a single interface, not to build a large and bloated interface, to refine the interface as much as possible, and to minimize the number of methods in the interface. In other words, we need to establish a dedicated interface for each class, rather than trying to create a huge interface for all classes that depend on it to call. In programming, relying on several dedicated interfaces is more flexible than relying on a comprehensive interface. Interface is a "contract" set externally at the time of design. Through the decentralized definition of multiple interfaces, it can prevent the spread of external changes and improve the flexibility and maintainability of the system.
At this point, many people will feel that the principle of interface isolation is very similar to the principle of single responsibility, but it is not. First, the principle of single responsibility originally focuses on responsibility, while the principle of interface isolation focuses on the isolation of interface dependence. Second, the principle of single responsibility is mainly the constraint class, followed by the interface and method, which aims at the implementation and details of the program, while the interface isolation principle mainly constrains the interface, mainly for abstraction and for the construction of the overall framework of the program.
When using the principle of interface isolation to constrain an interface, you should pay attention to the following points:
1. The interface should be as small as possible, but with limits. It is a fact that refinement of interfaces can improve the flexibility of programming, but if it is too small, it will cause too many interfaces and complicate the design. So it must be moderate.
two。 Customize the service for the class that depends on the interface, exposing only the methods it needs to the calling class, and hiding the methods it does not need. Only by focusing on providing customized services for a module can minimum dependencies be established.
3. Improve cohesion and reduce external interaction. Make the interface accomplish the most things in the least number of ways.
The principle of interface isolation must be moderate, and it is not good for the interface design to be too large or too small. When designing the interface, only by spending more time thinking and planning, can we accurately practice this principle.
Sunny software company developers for a CRM system customer data display module designed as shown in figure 1 interface, in which method dataRead () used to read data from the file, method transformToXML () used to convert the data into XML format, method createChart () used to create charts, method displayChart () used to display charts, method createReport () used to create text reports, method displayReport () used to display text reports.
Fig. 1 structure diagram of initial design scheme
It is found that the interface is very inflexible in practical use, for example, if a specific data display class does not need to perform data conversion (the source file itself is in XML format), but because of the implementation of the interface, you will have to implement the transformToXML () method declared in it (at least an empty implementation is required) If you need to create and display charts, you need to implement not only the methods related to charts, but also the methods of creating and displaying text reports, otherwise the program will report an error when compiling.
Now it is reconstructed using the principle of interface isolation.
In figure 1, because there are too many methods defined in the interface CustomerDataDisplay, that is, the interface undertakes too many responsibilities, on the one hand, the implementation class of the interface is so large that all the methods defined in the interface have to be implemented in different implementation classes, which is less flexible. if there are a large number of empty methods, it will lead to a large amount of useless code in the system and affect the quality of the code. On the other hand, because the client programming for the large interface will destroy the encapsulation of the program on a certain program, the client sees the method that should not be seen and does not customize the interface for the client. Therefore, the interface needs to be refactored according to the principle of interface isolation and single responsibility, and some of these methods are encapsulated in different small interfaces to ensure that each interface is more convenient to use and assume a single role. each interface contains only one method required by a client (such as a module or class).
By using the principle of interface isolation, the reconstructed structure of this example is shown in figure 2:
Fig. 2 structure diagram after reconstruction
6. Dimitt's rule (Law Of Demeter)
The basic idea of Demeter's rule is to emphasize the loose coupling between classes, the weaker the coupling between classes, the more conducive to reuse, a class in weak coupling is modified, it will not affect the related classes, that is to say, the hiding of information promotes the reuse of software.
Demeter's law requires that when designing a system, we should minimize the interaction between objects. If two objects do not have to communicate directly with each other, then the two objects should not have any direct interaction. If one of the objects needs to call a method of the other object, the call can be forwarded through a third party. In short, it is to reduce the coupling between existing objects by introducing a reasonable third party.
When applying Demeter's rule to system design, we should pay attention to the following points: in the division of classes, loosely coupled classes should be created as far as possible, and the lower the degree of coupling between classes, the more conducive to reuse. Once a class in loosely coupled is modified, it will not affect the associated class too much; in the structural design of the class, each class should minimize the access to its member variables and member functions. In class design, one type should be designed to be immutable whenever possible; in references to other classes, one object's references to other objects should be minimized.
Here is a simple example to deepen our understanding of Demeter's law:
The CRM system developed by Sunny Software Company contains many business operation windows, in which there are complex interactions between some interface controls. The trigger of a control event will cause a number of other interface controls to respond. For example, when a button (Button) is clicked, the corresponding list box (List), combo box (ComboBox), text box (TextBox), text label (Label) and so on will be changed. In the initial design scenario, the interaction between interface controls can be simplified to the structure shown in figure 1:
Fig. 1 structure diagram of initial design scheme
In figure 1, because of the complex interaction between interface controls, it is necessary to modify the source code of other controls that interact with when adding new interface controls in this window, so the system is not scalable and it is not easy to add and delete new controls.
It is now refactored using Demeter.
On the design patterns in Java which principles are shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.