I. Definition
The open and closed principle (OCP), which is the full name of open for Extention and closed for modification principle, that is, the principle of opening and closing for modification. The idea of this principle is that we can meet the changes through expansion without modifying the code, or when designing a module, this module should be extended without being modified.
II. Implementation
Abstraction is the key to implementing the open/closed principle. abstraction is a core feature of object-oriented design.
Abstract A thing is, in essence, a summary of its essence. Abstraction allows us to grasp the most important things and think from a higher level, which reduces the complexity of thinking and does not need to consider too many things at the same time.
Define an abstraction layer and define only functions without implementation. The implementation is accomplished by defining specific classes. When the demand changes, it is not done by modifying the abstraction layer, but by redefining the new Implementation of the abstraction layer, that is, through expansion. 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.
In this way, the abstract class and interface are used to specify the characteristics of a specific class as the abstract layer, which is relatively stable and does not need to be modified, so as to "Disable modification "; the specific Classes exported from abstract classes can change system behavior to meet the requirement of "open to extension ".
Even if the "open-close" principle cannot be fully implemented, efforts in this direction can significantly improve the structure of a system. On the other hand, it is not a good idea to abstract every part of the system. We should just abstract the parts with frequent changes in the program. Rejecting immature abstractions is as important as abstraction itself.
Iii. Benefits
1) by extending existing software systems, new behaviors can be provided to meet new demands for software and make the software systems in change adaptive and flexible.
2) the existing software modules, especially the most important abstract layer modules, cannot be modified any more, which makes the software system in change stable and continuous.
3) such a system also satisfies reusability and maintainability.
Iv. Summary
The key to implementing the open/closed principle is abstraction! The abstraction layer is relatively stable and does not need to be modified. After the requirement changes, the new Implementation of the abstraction layer is redefined.