设计模式之Composite模式(笔记)

组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用场合:当需求中是体现部分与整体层次的结构时,以及希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑用组合模式。
这里写图片描述
首先定义一个Componet抽象类

public abstract class Component {
    protected String name;

    public Component(String name){
        this.name=name;
    }
    //抽象方法
    public abstract void add(Component c);
    public abstract void delete(Component c);
    public abstract void dispaly(int depth);
}

定义叶结点对象Leaf,继承Componet

public class Leaf extends Component {

    public Leaf(String name) {
        super(name);

    }

    @Override
    public void add(Component c) {
        System.out.println("can not add a leaf");

    }

    @Override
    public void delete(Component c) {
        System.out.println("can not delete a leaf");

    }

    @Override
    public void dispaly(int depth) {
        char[] ch=new char[depth];
        for(int i=0;i<depth;i++){
            ch[i]='-';
        }
        System.out.println(new String(ch)+name);        
    }
}

结点定义枝结点Composite继承Component

public class Composite extends Component{

    private List<Component> children=new ArrayList<Component>();
    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component c) {

        children.add(c);
    }

    @Override
    public void delete(Component c) {
        children.remove(c);

    }

    @Override
    public void dispaly(int depth) {
        char[] ch=new char[depth];
        for(int i=0;i<depth;i++){
            ch[i]='-';
        }
        System.out.println(new String(ch)+name);
        Iterator<Component> iterator=children.iterator();
        while(iterator.hasNext()){
            Component component=iterator.next();
            component.dispaly(depth+2);
        }
    }
   }

客户端代码


       public static void main(String[] args) {
         //组合模式
        Composite root=new Composite("root");
        root.add(new Leaf("LeafA"));
        root.add(new Leaf("LeafB"));
        Composite comp=new Composite("Composite X");
        comp.add(new Leaf("LeafXA"));
        comp.add(new Leaf("LeafXB"));
        root.add(comp);

        Composite comp2=new Composite("Composite Y");
        comp2.add(new Leaf("LeafXYA"));
        comp2.add(new Leaf("LeafXYB"));
        root.add(comp2);

        root.add(new Leaf("LeafC"));

        root.dispaly(1);
}

结果:
-root
- - -LeafA
- - -LeafB
- - -Composite X
- - - - -LeafXA
- - - - -LeafXB
- - -Composite Y
- - - - -LeafXYA
- - - - -LeafXYB
- - -LeafC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值