The open-close principle (OCP) is called the cornerstone of OOD and is one of the most important principles of Ood.
This principle was proposed by Master Bertrand Meyer in 1988 (Khan, at that time I am afraid few people in China know Oo, or even what the computer is): software entities shocould be open for extension, but closed for modification. How simple ?! This principle means that the software should be developed for expansion, and the modification should be disabled. More broadly speaking, that is to say, we have developed a software that should be able to expand (open) its functions, no need to modify (close) the original program )!
Why is there such a requirement? If a software conforms to the OCP principle, we have at least two major benefits:
1. Flexible software availability. You can extend the software and add new features in the software. In this way, this software can meet the ever-changing new needs by constantly adding new modules!
2. Because the original module of the software cannot be modified, you do not have to worry about the stability of the software.
Currently, the main implementation of OCP isAbstractionThat is, we often talk about abstract (interface ). All possible behaviors of the system are abstracted into an abstract bottom layer, which specifies the features of methods required by all specific classes as the abstraction layer of system design, this abstraction layer needs to anticipate all possible extensions, so that the abstraction layer of the system does not need to be modified under any extension; at the same time, because one or more new classes can be exported from the abstraction layer to change the behavior of the system, the system design is open to expansion for the variable part.
The variable part of the system also provides a more detailed description of the variable encapsulation principle (principle of encapsulation of variation, EVP) from the perspective of engineering implementation. EVP requires evaluation and classification of all possible (or permitted) changes to the system during system design. Each variable is encapsulated separately.
It is easy to think that it is impossible (in fact, it is not cost-effective) to list all possible behaviors of the system at the beginning of the design ), it is not realistic to predict and encapsulate all variables. Therefore, it is difficult to fully implement the open/closed principle. It can only meet the requirements of OCP in some modules, to some extent, and to some extent. Therefore, OCP is idealistic and the ultimate goal of good. Therefore, for the Implementation Method of OCP, many masters of Ood are dedicated to studying the implementation method of OCP. The Rits replacement principle, merging and Reuse Principle, dependency inversion principle, interface isolation principle, abstract class, And Demeter rule mentioned later can be regarded as the implementation method of OCP.