1. Definition
In short, the definition of the merging/aggregation reuse principle is: Use synthesis and aggregation as much as possible, and do not use inheritance as much as possible.
2. Meaning
Why "we should try to use synthesis and aggregation instead of inheritance?
This is because:
First, inheritance reuse destroys the packaging. It exposes the implementation details of the parent class to the subclass, which violates the principle of information hiding;
Second, if the parent class changes, the Child class also changes accordingly, which directly leads to high coupling between the class and the class, it is not conducive to the extension, reuse, and maintenance of classes, and also brings about a rigid and fragile system design. During synthesis and aggregation, the interaction between new objects and existing objects is usually performed through interfaces or abstract classes, which can effectively avoid the above shortcomings, in addition, this allows each new class to focus on its own tasks and conform to the single responsibility principle.
3. When to use merging, aggregation, and inheritance
Two judgment methods:
1) Use "Has-A" and "Is-A" to determine
"Is-A" indicates that A class Is another class and can use an inheritance relationship, as shown in
"Has-A" indicates that A class is A role of another class, rather than A special class. For example
2) use the Li's replacement principle to judge
The Li's replacement principle is the basis for inheritance and reuse.
Specific Introduction: six principles of the design model-the Li's replacement principle