This is the 13th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Portfolio model

preface

Today we will learn the sixth type of structural pattern —- combination pattern.

Before exploring composition patterns, let’s review a few concepts, namely composition, inheritance, and aggregation.

  • Inheritance: It is the relationship of is A, in the case of the interface, the implementation. For example, cats are animals.
  • Aggregation: It represents the relationship between whole and parts, has a, e.g., a cat in the house. This relationship between the whole and the parts is not strongly dependent, and the home can be without cats.
  • Composition: It also reflects the relationship between the whole and the parts, but this relationship is stronger than aggregation. It emphasizes that the life cycle of the whole and the parts is the same, and the end of the life cycle of the whole means the end of the life cycle of the parts.

Okay, let’s get started on the combinatorial pattern.

First, combination mode entry

1.1 an overview of the

Composite patterns are often used to express the relationship between whole and parts. It is often used to represent a tree menu structure, which allows you to group objects into a tree structure and use them as individual objects.

So how do you think about it,

First, the composite pattern, which typically uses a common interface to interact with products and boxes. For example, there are many black boxes inside a product. For example, a computer consists of a host, keyboard, monitor and mouse.

The computer is a product, and these components are boxes for us. For the computer, we declare a method to calculate the total price; For box, we iterate through all the boxes to calculate the price of the mouse, display, keyboard, if the host is assembled, it may be that there are a lot of boxes, including memory, hard disk, etc., by the need to have access to the prices of these little black box, with the recursive approach to the prices of computer internal components, get in the end the price of the computer, We don’t have to worry about the complexity of the black box, we just call the same interface. The logic is similar to the following figure.

Now that we understand the definition of composite patterns, let’s look at the Wikipedia definition:

In software engineering, the composite pattern is a partition design pattern. A composite pattern describes a set of objects that are treated in the same way as a single instance of an object of the same type. The purpose of composition is to “compose” objects into a tree structure to represent a partial-whole hierarchy. Implementing the composite pattern allows the client to work uniformly with individual objects and combinations.

The composite pattern allows customers to work with individual objects and combinations uniformly. This is similar to our common tree directory assembly process.

As the latest outbreak strikes back, new cases are being added every day. The epidemic data I see now is as follows, in which we have made a preliminary statistics at the municipal level. If we want to calculate the new increment of local cases in China yesterday. This is where the composite pattern can be used. Let’s do this in code.

1.2 structure

1.2.1 role

There are three main types of roles in the composite mode:

  • Abstract root node: Defines common methods and properties for objects at all levels of the system, and can pre-define some default behaviors and properties
  • Tree nodes: Defines the behavior of tree nodes, stores child nodes, and combines tree nodes and leaf nodes to form a tree structure
  • Leaf node: Leaf node object, which has no further branches, is the smallest unit of system level traversal

1.2.2 Mode classification

According to the definition of abstract component class, composition pattern can be divided into transparent composition pattern and safe composition pattern:

  • Transparent combination pattern

    • In the transparent composite pattern, all methods for managing member objects are declared in the abstract root node role so that all trunk and leaf objects have the same interface.
    • But the disadvantage is that it is not safe, such as adding subclasses, if the leaf element does not need to add the leaf this function, but it does have this interface, if the run time accidentally call may report an error
  • Security combination mode:

    • In safe mode, the abstract component role does not declare any methods for managing member objects, but manages and implements these methods in the branch class. The disadvantage of safe mode is that it is not transparent, and leaves and containers must be treated differently.

1.3 Application Scenarios

The roles and categories of composite patterns have been analyzed above, and the following scenarios are used.

Combination mode is born for the tree structure, so the applicable scenario of combination mode is the place where the tree structure appears, such as: file directory display, multi-level directory rendering and other operations of tree structure data. It can be summarized as the following two:

  • Where it is necessary to represent a hierarchy of whole and parts of an object
  • In cases where a uniform interface is required for all objects in a composite structure to the user.

1.4 the advantages and disadvantages

Advantages:

  • The composite pattern can clearly define hierarchical complex objects, representing all or part of an object’s hierarchy. It allows the client to ignore the differences in hierarchies and facilitate control over the entire hierarchy.
  • The client can consistently use a composite structure or a single object within it without caring whether it is dealing with a single object or the entire composite structure, simplifying the client code.
  • It is convenient to add new branches and leaves to the composite pattern without any modification to the existing class library, complying with the “open closed principle”.
  • The combination pattern provides a flexible solution for the object-oriented realization of tree structure. Through the recursive combination of leaf node and branch node, the complex tree structure can be formed, but the control of the tree structure is very simple.

Disadvantages:

  • The client needs to spend more time sorting out the hierarchy between classes.
  • It is not easy to restrict builds in containers.
  • It is not easy to use inheritance to add new functionality to a build.
  • It is difficult to restrict the types of components in a composition.

Ii. Case study

Next, let’s implement this case of epidemic statistics with a combination model.

Let’s pick two provinces and one city for a demonstration. We need to figure out the total number of infected people in two provinces and one city.

The test class:

Public class Test {public static void main (String [] args) {/ * * * number screening outbreak of several cities, * China yesterday local epidemic feature: * | - jiangsu: 38 * - yangzhou: 37 * - nanjing: 1: * | - Taiwan | - hubei: 22 * 10 * - wuhan - - jingmen: 4 * 6 * | -... */ int sum =0; Component China = new Component(" China "); Component js = new Component(" "); City nj = new City(1, "nanjing "); City yz = new City(37, "yangzhou "); js.add(nj); js.add(yz); City tw = new City(22, "Taiwan "); Component hb = new Component(" hubei "); Where = new (4, "wuhan "); City jm = new City(6, "jingmen "); hb.add(wh); hb.add(jm); china.add(js); china.add(tw); china.add(hb); System.out.println(" number of infected people: "+china.count()); }}Copy the code

Leaf components: cities

/** * @author xiaolei ** * public class implements Counter{private int implements sum =0; Private String name; public City(int sum,String name){ this.sum=sum; this.name=name; } public int count() { return sum; }}Copy the code

Trunk component: container

public class Component implements Counter{ private String name; private ArrayList<Counter> arrayList =new ArrayList<Counter>(); public Component(String name){ this.name=name; Public void add(Counter Counter){arrayList.add(Counter); } public int count() {int sum=0; for (Counter counter : arrayList) { sum+=counter.count(); } return sum; }}Copy the code

Abstract component:

Public interface Counter {int count(); }Copy the code

Output results:

Number of infections yesterday: 70Copy the code

Third, summary

The combination pattern deals with combinations of whole and parts. If leaves artifacts and trunk components have many differences, such as a lot of properties and methods are different, can not apply it, and apply it can be very convenient processing tree structure, three examples mentioned in this article, a directory is the folder hierarchy, one is the price of the computer calculation, and an epidemic infection statistical calculations. These easy-to-understand examples help us quickly understand the composite pattern.

Design pattern itself has certain difficulty in the application, need certain business experience, if one day you suddenly revealed in which the underlying source code which you read mode, the value, if which day, you in the face of the business was in a hurry, suddenly the forehead a beat, ah, maybe a combination model, that you may be insight, hope that one day a little closer to you.

Finally, I wish an early end to the epidemic!!

The interactive link

  • If my article is useful to you, please give me a point 👍, thank you 😊!
  • Feel free to let us know in the comments! 💪

Iv. Brief introduction to design mode series 👏👏👏

  • (1): The foundation of great oaks from little acorns
  • (2): Singleton patterns — there is only one example
  • (3): Factory pattern — the generation of instances to subclasses
  • (4): Prototype pattern — generate examples by copying
  • [Design Patterns] (5): Builder pattern — assembling complex examples
  • (6): Agency mode — look at the influence of intermediary
  • (7): Adapter mode — Let Obama see that the three-body is not a dream
  • (8): Decorator mode — nesting doll + “grasping cake case” quick introduction
  • (9): Bridge mode — re-entry by “grasping cake case”
  • [Brief Talk on design mode] (10): Appearance mode — the face of the whole!