组合模式Composite Pattern

组合模式(Composite Pattern),以称部分整体模式,属于结构型设计模式。

组合模式Composite Pattern_第1张图片


public class Human {
    private String name;
    private String des;

    private List<Human> humanList = new ArrayList<>();

    public Human(String name, String des) {
        this.name = name;
        this.des = des;
    }

    public void add(Human human) {
        humanList.add(human);
    }

    public void remove(Human human) {
        humanList.remove(human);
    }

    public List<Human> getHuman() {
        return humanList;
    }

    @Override
    public String toString() {
        return "Human{" +
                "name='" + name + '\'' +
                ", des='" + des + '\'' +
                '}';
    }
}
public class CompositePatternDemo {
    public static void main(String[] args) {
        Human china = new Human("中国", "中国人");
        Human han = new Human("汉", "汉族");
        Human man = new Human("满", "满族");
        china.add(han);
        china.add(man);
        System.out.println(china);
        for (Human human : china.getHuman()) {
            System.out.println(human);
        }
    }
}

运行结果:
组合模式Composite Pattern_第2张图片

你可能感兴趣的:(设计模式,设计模式,组合模式)