The six principles of "Open and Close Principle (OCP)"

definition

​Open Closed Principle, the English abbreviation OCP, the full name is Open Closed Principle.

原始定义:Software entities (classes, modules, functions) should be open for extension but closed for modification。

Literal translation: Software entities (including classes, modules, functions, etc.) should be open for extension, but closed for modification.

Why "open" and "close"

Under normal circumstances, we receive notifications of changes in requirements. The usual way may be to modify the source code of the module. However, there is a great risk to modify the existing source code, especially after the project has been running for a period of time, the developer changes. This risk may be even greater. Therefore, in order to avoid this kind of risk, we generally do not modify the source code when facing changes in requirements, that is, the so-called closed for modification. It is not allowed to modify the source code, how do we respond to changes in requirements? The answer is that what we are going to say below is open to expansion.

To respond to changes in demand through expansion, we must be interface-oriented programming, or abstract programming. All parameter types and objects passed by reference must be defined in an abstract (interface or abstract class) way, and cannot be defined in the way of an implementation class; the extension is defined by abstraction. For example, if we define a parameter of interface A, then our extension is only It can be an implementation class of interface A. In general, the open-close principle improves the maintainability of the system and the reusability of the code.

Guess you like

Origin blog.csdn.net/qianzhitu/article/details/102987443