Big talk Design Pattern 1: first understanding the five basic principles of design pattern and Design Pattern
1. What is the design model?
Design pattern is a set of summary of code Design experiences that are repeatedly used, known to most people, classified and catalogued. Use design
The pattern is used to make code reusable, make it easier for others to understand, and ensure code reliability. There is no doubt that the design model is more than others than the system.
Winning; design patterns make code compilation truly engineered; design patterns are the cornerstone of software engineering, just like the building structure.
2. Why should we use the design mode?
Why do we advocate Design Pattern? The root cause is to reuse code and increase maintainability. So how can we achieve code reuse? Surface
There are several principles for moving objects: Single ResponsiblityPrinciple SRP, Open Closed Principle, OCP ),
LiskovSubstitution Principle, LSP, Dependency Inversion Principle, DIP, and interface isolation
Principle (Interface Segregation Principle, ISP), Composite/Aggregate Reuse Principle, CARP ),
The Principle of small Knowledge (Principle ofLeast Knowledge, PLK, also called the dimit rule ). The principle of openness and closure is idealistic, And it is object-oriented.
The ultimate goal of design. The other several items can be seen as the implementation method of the open and closed principle.
The design pattern is to achieve these principles, so as to achieve code reuse and increase maintainability.
Three design patterns five basic principles
Before learning the design pattern, we should first clarify that the pattern is object-oriented, and its three main features are encapsulation, inheritance, and polymorphism. The object-oriented design modes include:
Five basic principles: single responsibility principle, open and closed principle, dependency inversion principle, interface isolation principle, and Rishi replacement principle. The design model we learned is
The specific implementation derived from the object-oriented features and the five basic principles, it is necessary to introduce the basic concepts of several principles before learning.
(1) single responsibility principle (SRP)
1SRP definition: for a class, there should be only one reason for its change. In short, the function should be single.
2. If a class has too many responsibilities, it is equivalent to coupling these responsibilities. A change in responsibilities may weaken or suppress the completion of this class.
Other responsibilities. This coupling will lead to a fragile design. When a change occurs, the design will suffer unexpected damages. (Agile Software Development)
3. Much of software design really needs to do is to discover responsibilities and separate those responsibilities from each other. (Agile Software Development)
4. The single responsibility principle can be seen as the extension of low coupling and high cohesion in the object-oriented principle. The responsibility is defined as the cause of change to improve
Clustering to reduce the cause of changes. There are too many responsibilities, and there may be more reasons for its change. This will lead to the dependency between duties and the original
Because it greatly damages the cohesion and coupling.
5. Whether in design, interface, or method, a single responsibility is reflected everywhere. A single responsibility is defined as the original responsibility for system changes.
Because. When defining classes, interfaces, and methods. After the definition is complete, think about it again. There is no more motivation to change this class, interface, and method.
If the answer is yes, the defined class, interface, and method have more than one responsibility. Therefore, it violates a single responsibility. In this case, you should subscribe to the job.
Responsibility until there are no classes or interface methods with multiple responsibilities (discover responsibilities and separate those responsibilities ). A single responsibility is the simplest five
. It is embodied everywhere in the software design process. Everywhere.
(2) principle of opening/closing (OCP)
1OCP definition: that is, software entities (classes, methods, and so on) should be extensible, but cannot be modified. It is also the most important software design.
Design principles.
Two features of 2OCP:
A is open for expansion.
B. The modification is closed.
3. When Will OCP principles be applied?
When we first write the code, assuming that the changes do not happen, when the changes occur, we create an abstract (such as an abstract class, interface, etc.) to isolate
Similar changes.
4. The open/closed principle is the core of object-oriented design. Following this principle can bring about the huge benefits claimed by the object-oriented technology, that is, the feasibility
Protection, scalability, reusable, and flexible. Developers should only abstract those parts that present frequent changes in the program. However
It is also not a good idea to deliberately abstract each part of the sequence. Rejecting immature abstractions is just as important as abstraction itself.
5. The open/closed principle means that classes, modules, and methods can be expanded, but cannot be modified. It is open to expansion, and closed to modification. Principle of opening/closing
The application is embodied in that developers should abstract the frequent changes in the Program (encapsulate the change points ). Encapsulation of change points refers to modification of changes
Change to close. Uncertainty of changes can be expanded at any time. That is, the use of inheritance. The use of abstract classes.
UML diagram of 6OCP:
(3) lean replacement principle (LSP)
1LSP definition: child types must replace their parent types. Simply put, this is because the child type inherits the parent class, so sub-classes can
The parent class ID appears.
2. Any base class can appear, and a subclass can certainly appear. LSP is the cornerstone of inheritance and reuse. Only when the metadata class can replace the base class, the software
When the functions of a unit are not affected, the base class can be reused, and the category class can also add new behaviors based on the base class. Lee's replacement principle is
Supplement the principle of opening/closing. The key step for implementing the open and closed principles is abstraction. The inheritance relationship between the base class and the subclass is the specific implementation of abstraction.
The replacement principle is a standard for specific steps to achieve abstraction.
3. Implementation of the replacement principle. For a group of classes with similar attributes, methods, and variables. We can extract public attributes, methods, and variables as a base
Class (abstract class or class), so that this group of classes inherits the base class, override the virtual method. Currently, the relationships between these inherited classes and the base classes comply with Is-. If the base class is an animal
The inheritance class can be a dog or a cat. We can say that the cat Is-A, the dog Is-.
4. instance UML diagram:
Java code:
// Animal parent class Animal {public void eat () {} public void drink () {} public void run () {} public void shout () {}}// Cat subclass class Cat extends Animal {}// Dog subclass class Dog extends Animal {}// Cattle subclass class Cattle extends Animal {}// Sheep subclass class Sheep extends animal {} public class Test {public static void main (String [] arge) {Animal animal = new Cat (); // you can replace it with Dog, Cattle, or Sheep as needed. animal does not need to be changed elsewhere in the program. eat (); animal. drink (); animal. run (); animal. shout ();}}
5. Summary: All sub-classes in the project can be replaced by the parent class, but the method is called to present the polymorphism of object-oriented programming. That is
Lee's replacement principle is a very important principle and a relatively difficult principle.
(4) Dependency inversion principle (DIP)
1DIP definition: Abstraction should not depend on details, and details should depend on abstraction. High-level modules should not depend on low-level modules. Both of them should depend on
Abstract. Simply put, we need to program the interface instead of the implementation.
2 reverse example UML diagram:
Disadvantage: the High-Level module is too dependent on the low-level module, and the coupling is too tight. Changes to the lower-level modules will affect the upper-level modules.
Solution: Use the Dependency inversion principle to make the high-level and low-level modules depend on abstraction (interfaces or abstract classes ).
The modified UML diagram is as follows:
Advantage: modifying the lower-level modules will not affect the upper-level modules, reducing the Coupling Degree between them and enhancing the system stability.
3. analyze and design in a process-oriented development language, and always create some high-level modules to call low-level modules, and the policies depend on detailed software structures.
In fact, the purpose of this method is to define the subprogram hierarchy, which describes how the high-level module calls the lower-level module. The well-designed
The program of the image is "inverted". The dependency between the module and the module is no longer dependent on the lower-layer module. Therefore, the modification of the lower-layer module does not affect the upper-layer module,
In addition, high-level modules can be easily reused. Both high-level modules and low-level modules depend on abstraction. This is also very suitable for strong cohesion and loose coupling.
Programming ideology. Therefore, this principle is also the core principle of framework design.
Using the dependency structure created by the traditional procedural program design, the strategy depends on the details. This is bad because it will make the strategy
Affected by the changes in details, the object-oriented programming inversion of the dependency structure, full details and policies are dependent on abstraction, and often the customer Program
Has service interfaces. In fact, the inversion of this dependency is exactly the sign of a good object-oriented design. It is irrelevant to the language used for programming.
Yes. If the program dependency is inverted, it is an object-oriented design. If the program dependency is not inverted, it is a procedural setup.
.
4. The dependency inversion principle is a basic low-layer mechanism that implements the benefits declared by many object-oriented technologies. Its correct application applies to the creation of reusable frameworks
Required. At the same time, it is also very important for building flexible code in the face of changes, because the abstraction and details are isolated from each other, so the code is not
It is often easy to maintain.
5. Conclusion: The dependency inversion principle is actually a sign of object-oriented design. It is not important to use the language to compile the program.
It is how to implement abstract programming rather than detailed programming, that is, all dependencies in the program end with abstract classes or interfaces, that is, object-oriented
The opposite is procedural design.
(5) interface isolation principle (ISP)
Definition of 1 ISP: In the example of a customized service, each interface should be a role, not many, and should not do anything that should not be done.
2. It is better to use multiple dedicated interfaces than to use a single total interface. The dependence of a class on another class should be based on the smallest interface.
An interface represents a role and should not assign different roles to an interface. Unrelated interfaces are merged to form a bloated large connection
Port, which is a pollution to roles and interfaces. Customers should not be forced to rely on methods they do not need. An interface belongs to a customer and does not belong to its class hierarchy
Structure. This is quite clear. In other words, do not force customers to use the methods they do not use. If you force users to use the methods they do not use
These customers will face the changes caused by the changes to these unused methods.
3 It should be said that this principle is to deal with the shortcomings of the existing "fat" interface. If the class interface is not cohesive, it indicates that the class has a "fat" interface. In other words
The "fat" interface can be divided into multiple groups of methods. Each group serves a different set of customer programs. In this way, the customer program can use a group of Members.
Function, while other client programs can use member functions of other groups.
4. There are two methods for interface isolation (the sharing client is the splitting Interface ):
A uses the delegate (This delegate is not A. net delegate [delegate]) to separate the interface.
You can create a delegate class by using this class to implement methods in other interfaces after separation.
B. Use the multi-inheritance isolation interface,
This method divides the existing "fat" interface into two or more interfaces that can be called by different customer programs. If you need to implement multiple interfaces
Multiple inheritance is used for implementation. These two methods are all the methods for implementing interface isolation. The second method is common and simple. The first method
It is relatively complex to use, and duplicate objects are generated during the use of the Delegate, which takes up the running time and memory overhead. Sometimes
The two methods are required. The first method is unavailable. For example, the conversion made by using the delegate object is required, or it may need to be different in different situations.
.
Iv. Overview
(1) object-oriented design goals:
A. Scalability: with new requirements, new performance can be easily added to the system without affecting the existing performance or bringing new defects.
B flexibility: adding new function code changes occur smoothly without affecting other parts.
C alternative: some code in the system can be replaced with other classes of the same interface, without affecting the system.
(2) benefits of the design model:
A design pattern allows people to reuse successful designs and architectures more easily and easily.
B's design pattern also makes it easier for new system developers to understand their design ideas.
(3) The Learning and design model has three levels:
The first one: you are learning a design model and thinking about where I can use it in my new project (with a knife in your hands, without a knife in your mind)
Level 2: You have finished all the design patterns, but when you encounter a problem, you find that there are several design patterns for you to choose from.
There are knives in your mind)
Third: it is also the last one. You may not have the concept of a design pattern. There are only a few design principles in your mind.
The highest realm: no knife in the hands, no knife in the heart)