Just like the location of Newton's three major laws in classical mechanics, the open-closed principle is the cornerstone of object-oriented reusable design (Object Oriented Design or OOD. Other design principles (the Lee principle of substitution, the principle of dependency inversion, the principle of synthesis/aggregation reuse, the principle of Demeter, and the principle of interface isolation) are the means and tools for implementing the "open-closed" principle.
I. "Open-Closed principle (open-closed principle, OCP)1.1"Open-The definition and advantages of the "closed" Principle1) Definition: A software entity should be open to extensions and closed to modifications (software entities shocould be open for extension, but closed for modification .). That is, when designing a module, the module should be extended without being modified. 2) Advantages of systems that meet the "On-Off" principle a) by extending existing software systems, new behaviors can be provided to meet new software requirements, make the software system in change adaptive and flexible. B) existing software modules, especially the most important abstraction layer modules, cannot be modified any more, which makes the software systems in change stable and continuous. C) such a system meets both reusability and maintainability.
1.2How to Implement "open-Closed PrincipleIn object-oriented design, the abstraction layer of the system is not allowed to be changed, but the Implementation Layer of the system is allowed to be extended. In other words, define an abstract design layer once and for all to allow as many actions as possible to be implemented at the implementation layer. The key to solving the problem lies in abstraction. abstraction is the first core essence of object-oriented design. Abstract A thing is, in essence, a summary of its essence. Abstract Let us grasp the most important thing and think from a higher layer. This reduces the complexity of thinking. We don't need to consider so many things at the same time. In other words, we encapsulate the essence of things and cannot see any details. In object-oriented programming, abstract classes and interfaces are used to specify the features of a specific class as the abstract layer. This layer is relatively stable and does not need to be changed, so as to "Disable modification "; the specific class exported from the abstract class can change the behavior of the system to meet the requirement of "open to extension ". You do not need to modify the source code or binary code of the software when you expand an object. The key lies in abstraction.
1.3Encapsulation principles for variabilityThe "open-close" principle is the "encapsulation principle of variability" (principle of encapsulation of variation, EVP ). That is, find the variable factors of a system and encapsulate them. In other words, what changes may occur in your design should be encapsulated as an abstraction layer, rather than what will lead to design changes. "Encapsulation of variability" means: a variability should not be dispersed in many corners of the code, but encapsulated into an object. Different representations of the same variability mean that specific sub-classes in the same hierarchy are inherited. Therefore, we can look forward to the emergence of the inheritance relationship. Inheritance is a way to encapsulate changes, not just to generate special objects from general objects. B) One variability should not be mixed with another. The authors believe that if the inheritance structure of a class graph is more than two layers, it is likely that two different kinds of variability are mixed together. The design using the "variability encapsulation principle" can enable the system to comply with the "open-close" principle. Even if the "open-close" principle cannot be fully implemented, efforts in this direction can significantly improve the structure of a system.
Ii. liskov substitution principle, LSP)2.1ConceptDefinition: if there is an object O2 of Type T2 for every object O1 of Type T1, so that all program P defined by T1 can be replaced by O2 for all objects O1, if the behavior of program P does not change, Type T2 is the child type of Type T1. That is, if a software entity uses a base class, it must be applicable to its subclass. Moreover, it cannot detect the differences between base class objects and subclass objects. That is to say, in the software, the base class is replaced with its subclass, and the behavior of the program remains unchanged. In turn, substitution is not true. If a software entity uses a subclass, it is not necessarily applicable to the base class. Where any base class can appear, subclass can certainly appear. Contract-based design, abstract the public part as the abstract base class design.
2.2Li's replacement principle and "start-up-Closed "principle relationshipThe key step for implementing the "open-close" principle is abstraction. The inheritance relationship between the base class and the subclass is an abstract embodiment. Therefore, the Li's replacement principle is a standard for specific steps to achieve abstraction. Violation of the Li's replacement principle means violation of the "open-close" principle, and vice versa.
III,Dependency reversal Principle(Dependence inversion principle, dip)3.1ConceptDependency reversal PrincipleIt depends on abstraction rather than implementation. (Export actions shocould not depend upon details. Details shocould depend upon extends actions.) You must program the interface instead of the implementation programming. (Program to an interface, not an implementation.) That is to say, the interface and abstract class should be used for variable type declaration, parameter type declaration, method return type description, and data type conversion. Instead of using a specific class for type declaration, parameter type declaration, method return type description, and data type conversion. To ensure this, a specific class should only implement the methods declared in the interfaces and abstract classes, rather than providing redundant methods. The traditional process system design method tends to make high-level modules depend on low-level modules, and abstract layers depend on specific layers. The reverse principle is to reverse the dependency of this error. An important principle of object-oriented design is to create abstraction, export the specifics from abstraction, and give different implementations. An inheritance relationship is an export from abstraction to concrete. The abstraction layer should include the business logic of the application system and macro strategic decisions that are important to the entire system, and reflect the inevitability. Specific layers include secondary Implementation-Related Algorithms and logic, as well as tactical decisions, with a considerable chance to choose. The code at the specific level is frequently changed and errors cannot be avoided. From the perspective of reuse, high-level modules should be reused and the focus of reuse, because they contain the most important macro business logic of an application system and are relatively stable. In the traditional process design, reuse focuses on the reuse of specific levels of modules. The dependency reversal principle is an "reversal" of traditional procedural design methods and an effective standard for High-level module reuse and maintainability. Special case: the object creation process violates the "open-closed" principle and the dependency reversal principle. However, through the factory mode, the dependency inversion problem in the object creation process can be well solved.
3.2LinkThe "Open-Close" principle is related to the dependency reversal principle as the goal and means. If the principle of open and closed is the goal, the principle of dependency reversal is the means to reach the principle of "open and closed. To achieve the best "open and closed" principle, we should try to abide by the dependency reversal principle. The dependency reversal principle is the best criterion for "abstraction. The Li's replacement principle is the basis of the reversal principle, and the reversal principle is an important supplement to the Li's replacement principle.
3.3Types of coupling (or dependency) relationships:Zero-coupling (nil coupling) Relationship: two classes have no coupling relationship. The specific coupling relationship occurs between two (instantiated) classes, this is caused by direct reference of one class to another. Abstract coupling relationship: occurs between a specific class and an abstract class (or interface), so that two classes that must have a relationship have the maximum flexibility.
3.3.1 how to grasp CouplingWe should avoid inheritance as much as possible for the following reasons: 1. Losing flexibility and using specific classes will cause trouble for underlying modification. 2. Coupling refers to a measurement in which two entities depend on each other. Programmers Make decisions that affect coupling every day (consciously or unconsciously): Class coupling, API coupling, application coupling, and so on. In an extended inheritance implementation system, the derived class is very closely coupled with the base class, and this close connection may not be expected. For example, B extends a. When B does not use all the methods in A, the method called by B may produce errors! We must objectively evaluate the coupling degree, and the system cannot always be loosely coupled, so nothing can be done.
3.3.2 what is the basis for determining the degree of coupling?? Simply put, the coupling degree is determined based on the stability of the requirement. For those with high stability requirements that are not easy to change, we can design various types into tightly coupled ones (although we discuss the coupling between classes, but in fact, the coupling between functional blocks, modules, and packages is the same), because this can improve efficiency, and we can also use some better technologies to improve efficiency or simplify code, for example, internal technology in C. However, if the demand is very likely to change, we need to fully consider the coupling problem between classes. We can come up with various ways to reduce the coupling degree, but in summary, simply add an abstract level to isolate different classes. The abstract level can be an abstract class, a specific class, an interface, or a group of classes. We can summarize the idea of reducing Coupling Degree in one sentence: "programming for interfaces, rather than programming for implementation. When coding, we will leave our fingerprints, such as the number of public items and the code format. We can coupling metrics to evaluate the risk of re-building code. Because re-building is actually a form of maintaining the code, the troubles encountered during maintenance will also be encountered during re-building. We know that most of the most common random bugs after rebuilding are caused by improper coupling. The greater the unstable factor, the greater the coupling degree. Certain types of instability = number of dependent classes/number of dependent classes = Total number of other classes compiled at the time of compilation
3.3.3 how to split a large system into a small SystemOne idea to solve this problem is to combine many classes into a higher-level unit to form a set of high cohesion and low coupling classes, this is an issue that should be taken into consideration during our design process! The goal of coupling is to maintain the one-way dependency, and sometimes we need to use bad coupling. In this case, you should carefully record the cause to help users of the code later understand the real cause of coupling.
3.4How can we reverse the dependency?Coupling in an abstract way is the key to the dependency reversal principle. Abstract Coupling Relationships always involve the inheritance of a specific class from an abstract class, and must be ensured that the class can be changed to its subclass in any reference to the base class. Therefore, the Li's replacement principle is the basis of the reversal principle. Coupling at the abstract level is flexible, but it also brings additional complexity. If a specific class is less likely to change, the benefits of abstract coupling are very limited, in this case, coupling is better. Hierarchical: all well-structured object-oriented architectures have clear hierarchical definitions, and each layer provides services in a group through a well-defined and controlled interface. Dependent on Abstraction: We recommend that you do not rely on specific classes, that is, all dependencies in the program should end with abstract classes or interfaces. 1. No variable should hold a pointer or reference pointing to a specific class. 2. No class should be derived from a specific class. 3. No method should overwrite the implemented methods in any of its base classes.
3.5Advantages and disadvantages of dependency reversal principlesThe dependency reversal principle is powerful, but it is not easy to implement. Because of dependency inversion, object creation is likely to use the object factory to avoid direct reference to specific classes. The use of this principle may also lead to a large number of classes, for engineers who are not familiar with object-oriented technology, maintaining such a system requires a better understanding of object-oriented design. The dependency inversion principle assumes that all specific classes will change, which is not always correct. Some specific classes may be quite stable and will not change. Applications using this specific class instance can depend on this specific type completely without creating an abstract type for this.
4. Merging/Aggregation Reuse Principle (Composite/aggregate Reuse PrincipleOrCarp)4.1ConceptDefinition: Use existing objects in a new object to make it a part of the new object. New objects are reused by delegating these objects. Synthesis/aggregation should be used first, and synthesis/aggregation should be used to make the system flexible. inheritance should be considered to achieve reuse. In the use of inheritance, we must strictly follow the Li's replacement principle. The effective use of inheritance will help you understand the problem and reduce the complexity. Abuse of inheritance will increase the difficulty of system construction and maintenance and the complexity of the system. If the two classes are "has-a" relationships, synthesis and aggregation should be used. If the two classes are "is-a" relationships, inheritance can be used. "Is-a" is strictly defined in the taxonomy meaning that one class is another class "one ". "Has-a" is different. It indicates that a role has a certain responsibility.
4.2What is synthesis? What is aggregation?Both composition and aggregation are special types of association. Aggregation indicates the relationship between the whole and the part, indicating "having ". For example, the relationship between the s360 engine and the s360 tire is an aggregation relationship. When the s360 engine is left, the engine and tires become meaningless. In the design, aggregation should not occur frequently, which will increase the Coupling Degree of the design. Synthesis is a stronger "possession", which is similar to the overall life cycle. New merged objects have full control over their components, including their creation and destruction. The component object of a compositing relationship cannot be shared with another compositing relationship. In other words, synthesis is the aggregation by value, while generally speaking, aggregation is the reference aggregation by reference ). Understand the relationship between synthesis and aggregation, and then understand the principles of synthesis and aggregation. To avoid the emergence of a class in system design, there must be more than three layers of inheritance, you need to consider restructuring the code or re-designing the structure. Of course, the best way is to consider using the synthesis/aggregation principle.
4.3By merging/Advantages and disadvantages of aggregationAdvantages:1) The only way for a new object to access a component object is through the component object interface. 2) This reuse is black box reuse, because the internal details of the component object are invisible to the new object. 3) This reuse supports packaging. 4) This reuse requires less dependencies. 5) each new class can focus on a task. 6) This reuse can be performed dynamically during the running time. New objects can dynamically reference objects of the same type as component objects. 7) as a means of reuse, it can be applied to almost any environment.
Disadvantages:That is, many objects need to be managed in the system.
4.4Advantages and disadvantages of reuse through inheritanceAdvantages:The new implementation is easier, because most of the functions of the superclass can automatically enter the subclass through the inherited relationship. It is easier to modify and extend the inherited implementations.
Disadvantages: Inheritance reuse destroys the packaging, because inheritance exposes the implementation details of the super class to the subclass. Because the internal details of superclasses are often transparent to sub-classes, this reuse is transparent, also known as "white box" reuse. If the superclass changes, the implementation of the subclass also has to change. The implementation inherited from the superclass is static and cannot be changed during the running time. There is not enough flexibility. Inheritance can only be used in a limited environment.
V,Dimit law (Law of Demeter,Levels)
5.1OverviewDefinition: A software entity should interact with other entities as little as possible. In this way, when a module is modified, it will affect other modules as little as possible. Expansion is relatively easy. This is a restriction on communication between software entities. It requires limiting the width and depth of communication between software entities.
5.2Other statements of the dimit rule:1) only communicate with your friends directly. 2) do not talk to strangers. 3) each software organization has only the minimum knowledge of other units and is limited to software units closely related to the same unit.
5.3Dimit law in a narrow senseIf the two classes do not need to communicate with each other directly, the two classes should not interact directly. If one of the classes needs to call a method of another class, the call can be forwarded by a third party. Condition for determining "friends" in the circle of friends: 1) the current object itself (this) 2) is passed into the object in the current object method as a parameter 3) the instance variable of the current object directly references the object 4) if the instance variable of the current object is an aggregation, then the elements in the aggregation are also friends 5) Any object created by the current object, if one of the above conditions is met, it is the "friend" of the current object; otherwise it is a "stranger ". Disadvantages: a large number of small methods will be created in the system and scattered in every corner of the system. Complementary use with dependency reversal principles
5.4Disadvantages of the Demeter law in a narrow sense:A large number of small methods are created in the system. These methods only transmit indirect calls and are irrelevant to the business logic of the system. Following the dimit rule between classes will simplify the local design of a system, because each part will not be directly associated with a long-distance object. However, this will also reduce the communication efficiency between different modules of the system and make it difficult to coordinate different modules of the system.
5.5Dimit rules and Design PatternsThe facade (appearance) mode and the mediation (intermediary) mode are actually specific applications of the dimit law.
5.6Dimit law in a broad senseThe primary purpose of the dummit rule is to control information overload. When applying the Demeter rule to system design, pay attention to the following points: 1) In terms of Class division, a class with weak coupling should be created. 2) In the structure design of classes, each class should minimize the access permissions of members. 3) in the design of classes, a class should be designed as a constant class as long as possible. 4) When referencing other classes, the reference of an object to its object should be minimized.
5.7The embodiment of the general Demeter law in class design1) Prioritize setting a class to a class unchanged. 2) Minimize the access permissions of a class. 3) exercise caution when using serializable4. Minimize the access permissions of Members. 5) the replacement of the C struct Dirichlet principle is also called the least knowledge principle (least knowledge principle or abbreviated as LKP). That is to say, an object should have as little knowledge as possible for other objects.
5.8How to Implement the dimit ruleThe primary purpose of the dimit rule is to control information overload. When applying it to the system design, pay attention to the following points: 1) in the Division of classes, weak coupling classes should be created. The weaker the coupling between classes, the more conducive it is to reuse. 2) In the structure design of classes, each class should minimize the access permissions of members. A class should not have its own public attributes. Instead, it should provide a method of value and value assignment to allow the outside world to indirectly access its own attributes. 3) in the design of classes, a class should be designed as a constant class as long as possible. 4) When referencing other objects, the reference of a class to other objects should be minimized.
VI,Interface isolation principle (Interface separate principle, ISP)6.1ConceptInterface isolation principle: it is better to use multiple special interfaces than to use a single total interface. That is to say, the dependence of a class on another class should be based on the smallest interface. The "interface" usually has two different meanings: one is a set of method features of a type, which is just a logical abstraction; the other is the specific "interface" definition in a language with strict definitions and structures. For example, the interface structure in C. ISP expressions and meanings are different for these two meanings. (The type mentioned above can be understood as a class. We define a class, that is, a new type) when we understand an "interface" as a feature set of all methods provided by a Class, this is a logical concept. The division of interfaces directly leads to the division of types. Here, we can understand an interface as a role. An interface only represents a role, and each role has a specific interface. Here, this principle can be called "role isolation principle ". If "interface" is understood as an interface in a specific language in a narrow sense, the ISP expresses that different interfaces are provided for different clients and roles, that is, customized services and personalized services. It only provides the behavior required by the client, and the behavior not required by the client is hidden. The client should be provided with an independent interface as small as possible, rather than a large total interface. This is also a limitation on communication between software entities. But it only limits the communication width, that is, the communication should be as narrow as possible. Compliance with the dimit rule and the interface isolation principle will make a software system function extension, the pressure of modification will not be transferred to other objects.
6.2How to Implement the interface isolation principleUsers should not be forced to rely on methods they do not need. 1. Use the delegate isolation interface. 2. Use the multi-inheritance isolation interface.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.