


Detailed graphic explanation of the principles of composition, aggregation and reuse in Java
This article mainly introduces the principles of synthesis, aggregation and reuse. The editor thinks it is quite good. I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Principle of synthesis, aggregation and reuse
The principle of synthesis and reuse is also called the principle of combination/aggregation and reuse (Composition/ Aggregate Reuse Principle (CARP), which is defined as follows:
Composite Reuse Principle (CRP): Try to use object combination instead of inheritance to achieve the purpose of reuse.
The principle of synthesis and reuse is to use some existing objects in a new object through association relationships (including combination relationships and aggregation relationships) to make them part of the new object; The new object achieves the purpose of reusing functions by calling methods of existing objects through delegation. In short: When reusing, try to use combination/aggregation relationships (association relationships) and use less inheritance.
In object-oriented design, there are two ways to reuse existing designs and implementations in different environments, namely through composition/aggregation relationships or through inheritance, but you should first consider using composition /Aggregation, combination/aggregation can make the system more flexible, reduce the coupling between classes, and changes in one class will have relatively little impact on other classes; secondly, consider inheritance. When using inheritance, you need to strictly follow the rules According to the principle of substitution, effective use of inheritance will help understand the problem and reduce complexity, while abuse of inheritance will increase the difficulty of system construction and maintenance and the complexity of the system. Therefore, inheritance reuse needs to be used with caution.
The main problem with reuse through inheritance is that inheritance reuse will destroy the encapsulation of the system, because inheritance will expose the implementation details of the base class to the subclass, because the internal details of the base class are usually not visible to the subclass. is visible, so this kind of reuse is also called "white box" reuse. If the base class changes, then the implementation of the subclass will also have to change; the implementation inherited from the base class is static and does not It may change at runtime and is not flexible enough; and inheritance can only be used in limited circumstances (for example, a class is not declared as not inheritable).
Extension
For an in-depth understanding of inheritance, you can refer to the article by Mr. Wen Yu, the author of "Software Architecture Design" - " Seeing the mountains is just mountains and seeing water is just water - Improving the understanding of inheritance".
Since the combination or aggregation relationship can incorporate existing objects (also called member objects) into new objects and make them part of the new object, the new object can call the functions of the existing objects. Doing so can make the internal implementation details of the member object invisible to the new object, so this kind of reuse is also called "black box" reuse. Compared with the inheritance relationship, its coupling degree is relatively low, and changes in the member object have no impact on the new object. The impact is not big, and the operations of member objects can be selectively called in new objects according to actual needs; synthetic reuse can be performed dynamically at runtime, and new objects can dynamically reference other objects of the same type as member objects.
Generally speaking, if the relationship between two classes is "Has-A", combination or aggregation should be used, and if there is an "Is-A" relationship, inheritance can be used. "Is-A" is a strict taxonomic definition, meaning that one class is "a kind" of another class; "Has-A" is different, it means that a certain role has a certain responsibility.
The following is a simple example to deepen our understanding of the principle of synthesis and reuse:
In the initial design of the CRM system, the developers of Sunny Software Company took into account the small number of customers. The system uses MySQL as the database. Classes related to database operations such as the CustomerDAO class need to connect to the database. The method getConnection() for connecting to the database is encapsulated in the DBUtil class. Since the getConnection() method of the DBUtil class needs to be reused, the designer uses CustomerDAO as A subclass of the DBUtil class, the initial design plan structure is shown in Figure 1:
Figure 1 Initial design plan structure chart
As customers As the number increases, the system decides to upgrade to the Oracle database, so a new OracleDBUtil class needs to be added to connect to the Oracle database. Since there is an inheritance relationship between CustomerDAO and DBUtil in the initial design plan, the CustomerDAO class needs to be modified when changing the database connection method. The source code uses CustomerDAO as a subclass of OracleDBUtil, which will violate the open-close principle. [Of course, you can also modify the source code of the DBUtil class, which will also violate the opening and closing principle. 】
Now use the principle of synthesis and reuse to reconstruct it.
According to the principle of synthetic reuse, we should use more associations and less inheritance when implementing reuse. Therefore, in this example we can use association reuse to replace inheritance reuse. The reconstructed structure is shown in Figure 2:
Figure 2 Reconstructed structure picture
In Figure 2, the relationship between CustomerDAO and DBUtil changes from inheritance to association. Dependency injection is used to inject the DBUtil object into CustomerDAO. You can use constructor injection or Setter injection. If you need to extend the functions of DBUtil, you can do so through its subclasses, such as connecting to the Oracle database through the subclass OracleDBUtil. Since CustomerDAO is programmed for DBUtil, according to the Liskov substitution principle, the object of the DBUtil subclass can overwrite the DBUtil object. You only need to inject the subclass object into CustomerDAO to use the methods extended by the subclass. For example, by injecting the OracleDBUtil object into CustomerDAO, the Oracle database connection can be realized. The original code does not need to be modified, and new database connection methods can be added flexibly.
The above is the detailed content of Detailed graphic explanation of the principles of composition, aggregation and reuse in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
