1. Basic introduction

  • The rule is to use composition/aggregation rather than inheritance whenever possible
  • The principle of composite reuse is also called the synthesis/polymerization principle. The principle is to use some existing objects in a new object and make them part of the new object, and the new object can reuse the existing function by delegating to these objects

2. The difference between synthesis and polymerization

  • Composition and polymerization are special cases of association. Aggregation is used to mean “owning” or whole to part; Synthesis is used to represent a much stronger “owning” relationship. In a composite relationship, the life cycles of the parts and the whole are the same. A synthesized new object has full control over its components, including their creation and destruction. In programming language terms. The composition of the new object is absolutely responsible for the memory allocation, memory release of the component

3. Basic types of reuse

1) Synthesis/polymerization multiplexing

  • Advantages The only way a new object can access a component object is through its interface; This reuse is black-box reuse because the internal details of the component object are invisible to the new object; This reuse supports packaging and requires fewer dependencies; Each new class can focus on one task; Reuse can occur dynamically at run time, and new objects can delegate new responsibilities to appropriate objects using composition/aggregation relationships.

  • Disadvantages A system built by reuse in this way has more objects to manage

2) Inheritance reuse

  • Advantages The new implementation is easier because most of the functionality of the base class can be automatically transferred to the derived class through inheritance relationships. It is easier to modify or extend the inherited implementation.
  • Disadvantages Inheritance reuse breaks packaging because inheritance exposes the implementation details of the base class to derived classes, also known as white-box reuse; If the implementation of the base class changes, the implementation of the derived class must also change; Implementations inherited from base classes are static, cannot be changed at run time, and are not flexible enough.