Software composition entities should be extensible, but cannot be modified.
[Software entities shocould be open for extension, yet closed for Modification
]
Openness-closure rules
1. The open-closed principle assumes that we should try to design modules that never need to be changed.
2. We can add newCodeTo expand the behavior of the system. We cannot modify the existing code.
3. OCP-compliant modules must meet two standards:
4. scalability, that is, "open for extension'-module behavior can be extended to meet new requirements.
5. unchangeable, that is, "the changes are closed" (closed for modification)-module'sSource codeModification is not allowed.
6. What can we do?
A. Abstract action)
B. Polymorphism)
C. Inheritance)
D. Interface)
7. All modules of a software system cannot satisfy the OCP, but we should try to minimize the number of modules that do not satisfy the OCP.
8. The open-closed rule is the core of OO design.
9. Compliance with this rule means the highest level of reusability and maintainability ).
OCP example
1. Consider the following methods:
2. The above function is used to calculate the total price of each component in the component array.
3. If a part is a base class or interface that uses polymorphism, this class can easily adapt to new types of components without having to modify them.
4. It will comply with the OCP
5. However, when calculating the total price, what should I do if the finance department issues additional fees for the main board and memory.
6. How is the following code implemented?
7. Does this comply with OCP?
8. Every time the Finance Department proposes a new pricing strategy, we have to modify the totalprice () method! This is not "Closed for changes ". Obviously, policy changes mean we have to modify the code in some places. So how should we do it?
9. To use totalprice () of our first version, we can merge the billing policy into the getprice () method of the part.
10. Here is an example of the part and concretepart classes:
11. But now every time the pricing policy changes, we must modify each subclass of the part!
12. A better idea is to use a pricepolicy class to provide different pricing strategies by inheriting it:
13. What we seem to do is to postpone the problem to another class. However, with this solution, we can dynamically set the pricing policy by changing the part object during running.
14. Another solution is to obtain the current price of each concretepart from the database or attribute file.
Radio rule
The single choice principle is an inference of OCP.
At any time, a software system must support a set of standby options. Ideally, only one class in the system can know the entire set of standby options.
From: http://doc.linuxpk.com/type212.html