"Design Patterns" Combination Patterns

"Design Patterns" Basic Principles of Design Patterns
"Design Patterns" Singleton Patterns "
Design Patterns" Factory Patterns
"Design Patterns" Prototype Patterns "
Design Patterns" Builder Patterns "Design Patterns
" Adapter Patterns "Design
Patterns" Bridge Patterns
"Design Patterns" "Decorator Mode
" Design Mode" Composition Mode
"Design Mode" Appearance Mode "Design Mode"
Flyweight Mode "Design Mode" Proxy Mode "
Design Mode
" Template Method Mode
"Design Mode" Command Mode

"Design Patterns" Combination Patterns

Definition :

  • Composite mode is a structural mode, also known as part-whole mode , which creates a tree structure of object groups and combines objects into a tree structure to represent the "whole-part" relationship.
  • The composition mode makes the user's access to individual objects and composite objects consistent , that is: composition allows customers to treat individual objects and composite objects in a consistent manner.

Combination mode mainly includes three roles :

  • Abstract root node (Component) : Define the public methods and properties of objects at all levels of the system, and some default behaviors and properties can be pre-defined.
  • Branch node (Composite) : Define the behavior of branch nodes, store child nodes, and combine branch nodes and leaf nodes to form a tree structure.
  • Leaf node (Leaf) : The leaf node object has no branches under it, and is the smallest unit of system hierarchy traversal.

Notes on composite mode :

  • Simplify client operations : clients only need to face consistent objects without considering the overall part or leaf nodes.
  • It has strong scalability : when it is necessary to change the combined object, it only needs to adjust the internal hierarchical relationship, and the client does not need to make any changes.
  • It is convenient to create a complex hierarchical structure : the client does not need to consider the details of the internal composition of the combination, and it is convenient to add nodes or leaves to create a complex tree structure.
  • The Composite pattern is great for traversing organizations or when dealing with objects that have a tree structure.
  • High abstraction is required . If there are many differences between nodes and leaves, for example, many methods and attributes are different, it is not suitable to use the combination mode.

The principle class diagram of the combination mode is as follows :

insert image description here

Now there is a requirement to print out the names of all menus and menu items (a menu item
refers to a menu item that does not contain other content) for a menu of a management system, and use the combination mode to realize this case.

insert image description here

kindMenuComponent

/**
 * 菜单组件:不管是菜单还是菜单项都应该继承菜单组件
 */
public abstract class MenuComponent {
    
    
    protected String name;
    protected int level;

    //添加菜单
    public void add(MenuComponent menuComponent) {
    
    
        throw new UnsupportedOperationException();
    }

    //删除菜单
    public void remove(MenuComponent menuComponent) {
    
    
        throw new UnsupportedOperationException();
    }

    //获取指定的子菜单
    public MenuComponent getChild(int i) {
    
    
        throw new UnsupportedOperationException();
    }

    //获取菜单名称
    public String getName() {
    
    
        return name;
    }

    public void print() {
    
    
        throw new UnsupportedOperationException();
    }
}
  • MenuComponent is defined as an abstract class, because there are some common properties and behaviors to be implemented in this class, and the Menu and MenuItem classes can only cover the methods they are interested in, without having to deal with the methods that they don't need or are not interested in.
  • The Menu class can contain submenus, so add()、remove()、getChild()the method , but MenuItem should not have these methods. The default implementation given here is to throw an exception, and you can also rewrite the default implementation according to your own needs.

kindMenu

public class Menu extends MenuComponent{
    
    
    private List<MenuComponent> menuComponentList;

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

    @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.println("--");
        }

        for (MenuComponent menuComponent : menuComponentList) {
    
    
            menuComponent.print();
        }
    }
}

The Menu class has implemented all methods except getName()the method , because the Menu class has the functions of adding menu, removing menu and getting submenu.

kindMenuItem

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

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

MenuItem is a menu item and cannot have submenus, so the functions of adding menu, removing menu and getting submenu do not need to be implemented.

When using the combination mode, according to the definition form of the abstract component class, the combination mode can be divided into two forms : transparent combination mode and safe combination mode :

  1. Transparent composition mode : In the transparent composition mode, all methods used to manage member objects are declared in the abstract root role, for example, the method MenuComponentis declared add() 、 remove()advantage of this is to ensure that all component classes have the same interface. The transparent composite mode is also the standard form of composite mode .
    The disadvantage of the transparent combination mode is that it is not safe enough : because the leaf object and the container object are essentially different, the leaf object cannot have objects of the next level, that is, it cannot contain member objects, so it is meaningless to provide methods add()、remove()such Yes, there will be no error during the compilation phase, but an error may occur if these methods are called during the runtime phase (if no corresponding error handling code is provided).

  2. Security combination mode : In the security combination mode, no method for managing member objects is declared in the abstract component role, but these methods are declared and implemented in the branch node Menu class. The disadvantage of the safe composition mode is that it is not transparent enough , because the leaf component and the container structure have different methods, and the methods used to manage member objects in the container component are not defined in the abstract component class, so the client cannot completely program against the abstraction, and must Treat leaf widgets and container widgets differently.

insert image description here

In addition, the combination mode is also applied in the JDK source code, and the collection class HahsMap uses the combination mode:

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43252521/article/details/127394036