Six Principles of Design Patterns - Open and Closed Principles

1. Overview of the open-closed principle

      The Open-Closed Principle (OCP) has two main characteristics: (1) Open to expansion: the behavior of the module can be expanded, and when the application requirements change, the module can be expanded

(2) Close to modification: When extending the module, the source code of the module does not need to be changed. The opening and closing principle is the cornerstone of reusable design in object-oriented design.

2. Realization of the open-closed principle

      The key to realizing the opening and closing principle is abstraction. Abstract base class: abstracts all possible behaviors of the system into an abstract bottom layer. This abstract bottom class specifies the characteristics of all methods that must be provided by specific implementations. As the abstraction layer of system design, all possible expansions should be foreseen, so that in any expansion case, the abstract bottom layer of the system does not need to be modified. Derived class: Derive one or more new concrete implementations from an abstract base class, which can extend the behavior of the base class, and the system design is open to extensions.

3. How to use the opening and closing principle

      Abstract constraints: (1) Constrain extensions through interfaces or abstract classes, limit the boundaries of extensions, and do not allow public methods that do not exist in interfaces or abstract classes. (2) Try to use interfaces or abstract classes for parameter types and reference objects instead of implementation classes. (3) The abstraction layer should be kept as stable as possible and no modification is allowed once it is determined.

       Let the design follow OCP principles for the most likely changes. Following OCP principles is expensive. Creating appropriate objects requires development time and effort. Abstractions increase software complexity and limit OCP applications to the changes that are most likely to occur.

4. Advantages of the opening and closing principle

(1) Reusability (2) Maintainability

Note: Refactoring that violates the open-closed principle can adopt design patterns: strategy pattern, template method pattern

Guess you like

Origin blog.csdn.net/u014086857/article/details/85648703