concept

Also known as the partial whole pattern, treats a group of similar objects as one object, provides a tree structure to combine objects, and then provides a unified method to access the corresponding objects, thus ignoring the differences between objects and collections of objects (View and ViewGroup).

implementation

  • Component — Abstract the root node. Defines the default behavior of interfaces common to all classes. (View)
  • Composite – The behavior of the branch nodes that define all the children (and children themselves). (ViewGroup)
  • Leaf — Leaf node (TextView)
public abstract class Component {
    public abstract void fun();
}

public class Composite extends Component{
    private List<Component> components = new ArrayList<>();

    @Override
    public void fun() {if(components ! = null){for(Component c : components) {
                c.fun();
            }
        }
    } 

    public void addChild(Component child){
        components.add(child);
    }
    // removeChild(), getChild()
}

public class Leaf extends Component {

    @Override
    public void fun(){
        System.out.println("myname"); } } public class Test { public static void main(String[] args){ Composite root = new Composit(); Composite branch1 = new Composit(); Composite branch2 = new Composit(); Leaf l1 = new Leaf(); Leaf l2 = new Leaf(); branch1.addChild(leaf1); branch2.addChild(leaf2); root.addChild(branch1); root.addChild(branch2); root.fun(); }}Copy the code