Six principles of design patterns-Principles of synthesis/aggregation reuse (CARP)

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.