14, Combination mode

Keywords: Java Design Pattern

0. Ma Xian inspirational

It is not circumstances that make people, but man-made circumstances.

1. General

I'm sure I'll be very familiar with this picture. The above figure can be regarded as a file system. For this structure, we call it a tree structure. In the tree structure, we can traverse the whole tree by calling a method. When we find a leaf node, we can perform relevant operations on the leaf node. This tree can be understood as a large container, which contains many member objects, which can be either container objects or leaf objects. However, due to the functional differences between container objects and leaf objects, we must distinguish between container objects and leaf objects in the process of use, but this will bring unnecessary trouble to customers. As customers, they always want to treat container objects and leaf objects consistently.

definition:

Also known as partial whole pattern, it is used to treat a group of similar objects as a single object. The combination mode combines objects according to the tree structure, which is used to represent the partial and overall levels. This type of design pattern is a structural pattern, which creates a tree structure of object groups.

2. Structure

The combination mode mainly includes three roles:

  • Abstract root node (Component): defines the common methods and attributes of objects at all levels of the system, and some default behaviors and attributes can be defined in advance.
  • Composite: defines the behavior of branch nodes, stores child nodes, and combines branch nodes and leaf nodes to form a tree structure.
  • Leaf node: leaf node object, under which there is no branch, is the smallest unit of system level traversal.

3. Case realization

[example] software menu

As shown in the figure below, we can often see similar menus when accessing other management systems. A menu can contain menu items (menu items refer to menu items that no longer contain other contents) or menus with other menu items. Therefore, it is appropriate to use the combination mode to describe the menu. Our requirement is to print out all the menus and menu item names for a menu.

To implement this case, we first draw a class diagram:

Code implementation:

Both menus and menu items should inherit from the unified interface, which is called menu component.

//Menu components, whether menus or menu items, should inherit this class
public abstract class MenuComponent {

    protected String name;
    protected int level;

    //add menu
    public void add(MenuComponent menuComponent){
        throw new UnsupportedOperationException();
    }

    //Remove menu
    public void remove(MenuComponent menuComponent){
        throw new UnsupportedOperationException();
    }

    //Gets the specified submenu
    public MenuComponent getChild(int i){
        throw new UnsupportedOperationException();
    }

    //Get menu name
    public String getName(){
        return name;
    }

    public void print(){
        throw new UnsupportedOperationException();
    }
}

The MenuComponent here is defined as an abstract class. Because there are some common properties and behaviors to be implemented in this class, the Menu and MenuItem classes can only cover the methods they are interested in, rather than the methods they are not interested in. For example, the Menu class can contain submenus, so they need to cover the add(), remove(), getChild() methods, But MenuItem should not have these methods. The default implementation given here is to throw exceptions. You can also rewrite the default implementation according to your own needs.

public class Menu extends MenuComponent {

    private List<MenuComponent> menuComponentList;

    public Menu(String name,int level){
        this.level = level;
        this.name = name;
        menuComponentList = new ArrayList<MenuComponent>();
    }

    @Override
    public void add(MenuComponent menuComponent) {
        menuComponentList.add(menuComponent);
    }

    @Override
    public void remove(MenuComponent menuComponent) {
        menuComponentList.remove(menuComponent);
    }

    @Override
    public MenuComponent getChild(int i) {
        return menuComponentList.get(i);
    }

    @Override
    public void print() {

        for (int i = 1; i < level; i++) {
            System.out.print("--");
        }
        System.out.println(name);
        for (MenuComponent menuComponent : menuComponentList) {
            menuComponent.print();
        }
    }
}

The Menu class has implemented all methods except the getName method, because the Menu class has the functions of adding menus, removing menus and obtaining submenus.

public class MenuItem extends MenuComponent {

    public MenuItem(String name,int level) {
        this.name = name;
        this.level = level;
    }

    @Override
    public void print() {
        for (int i = 1; i < level; i++) {
            System.out.print("--");
        }
        System.out.println(name);
    }
}

MenuItem is a menu item and cannot have sub menus. Therefore, the functions of adding menus, removing menus and obtaining sub menus cannot be realized.

4. Classification of combination mode

When using composite mode, according to the definition form of abstract component class, we can divide the composite mode into transparent composite mode and safe composite mode.

  • Transparent combination mode

    In the transparent composition mode, all methods for managing member objects are declared in the abstract root node role. For example, in the example, MenuComponent declares add, remove and getChild methods. The advantage of this is to ensure that all component classes have the same interface. Transparent composite mode is also the standard form of composite mode.

    The disadvantage of transparent composition mode is that it is not safe enough, because leaf objects and container objects are different in essence. Leaf objects cannot have objects at the next level, that is, they cannot contain member objects. Therefore, it is meaningless to provide them with methods such as add(), remove(). There will be no error in the compilation stage, but there may be an error if these methods are called in the run-time (if no corresponding error handling code is provided)

  • Safe combination mode

    In the security composition mode, no methods for managing member objects are declared in the abstract component role, but they are declared and implemented in the tree node Menu class. The disadvantage of the security composition mode is not transparent enough, because the leaf component and the container component have different methods, and the methods for managing member objects in the container component are not in the abstract component Class, so the client cannot program completely for abstraction, and must treat leaf components and container components differently.

5. Advantages

  • Composite mode can clearly define hierarchical complex objects and represent all or part of the hierarchy of objects. It allows the client to ignore the hierarchy differences and facilitate the control of the whole hierarchy.
  • The client can consistently use a composite structure or a single object in it, regardless of whether it is dealing with a single object or the whole composite structure, which simplifies the client code.
  • It is convenient to add new branch nodes and leaf nodes in the combination mode without any modification to the existing class library, which conforms to the "opening and closing principle".
  • The combination pattern provides a flexible solution for the object-oriented implementation of tree structure. Through the recursive combination of leaf nodes and branch nodes, complex tree structure can be formed, but the control of tree structure is very simple.

6. Usage scenario

The combination mode is based on the tree structure, so the use scenario of the combination mode is where the tree structure appears, such as file directory display, multi-level directory presentation and other tree structure data operations.

This blog comes from the summary of dark horse programmer's video tutorial and the arrangement of notes. It is only for learning and communication. It should not be used for commercial purposes. If there is infringement, please contact the blogger to delete it. Blogger QQ: 194760901

Posted by nike121 on Sun, 24 Oct 2021 11:01:41 -0700