大话设计模式-组合模式的实践-衣服

UML

服装类

/** * @ClassName: Clothes * @Author: Leo * @Description: * @Date: 2019/5/8 09:07 */
public abstract class Clothes {
    protected String name;

    public Clothes(String name) {
        this.name = name;
    }

    public abstract void add(Object object);

    public abstract void remove(Object object);

    public abstract void display(int depth);
}

服装节点 可以保存服装节点或者叶子节点

import java.util.ArrayList;
import java.util.List;

/** * @ClassName: Composite * @Author: Leo * @Description: 代表男装女装的类 可以继续组合其他 * @Date: 2019/5/8 09:10 */
public class Composite extends Clothes {
    private List<Composite> clothes = new ArrayList<>();
    private List<Leaf> leaves = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Object object) {
        if (object instanceof Leaf) {
            leaves.add((Leaf) object);
        } else if (object instanceof Composite) {
            clothes.add((Composite) object);
        }
    }

    @Override
    public void remove(Object object) {
        if (object instanceof Leaf) {
            leaves.remove(object);
        } else if (object instanceof Composite) {
            clothes.remove(object);
        }
    }

    @Override
    public void display(int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print(" ");
        }
        System.out.println("+" + name);
        for (Leaf leaf : leaves) {
            leaf.display(depth + 3);
        }
        for (Composite clothe : clothes) {
            clothe.display(depth + 1);
        }
    }
}

叶子节点 无法保存其他节点

/** * @ClassName: Leaf * @Author: Leo * @Description: 代表叶子节点 * @Date: 2019/5/8 09:10 */
public class Leaf {
    private String name;

    public Leaf(String name) {
        this.name = name;
    }

    public void display(int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print(" ");
        }
        System.out.println("-" + name);
    }
}

测试类

/** * @ClassName: Main * @Author: Leo * @Description: * @Date: 2019/5/8 09:07 */
public class Main {
    public static void main(String[] args) {
        Composite root = new Composite("服装");
        Composite c1 = new Composite("男装");
        c1.add(new Leaf("衬衫"));
        c1.add(new Leaf("T恤"));
        Composite c2 = new Composite("女装");
        c2.add(new Leaf("连衣裙"));
        c2.add(new Leaf("小花裙"));
        root.add(c1);
        root.add(c2);
        root.display(0);
    }
}

运行结果

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务