设计模式课时四------组合模式

组合模式

定义:组合模式(又为 ‘整体-部分’ 模式)屏蔽了容器对象与单个对象在使用时的差异,为客户端提供统一的操作接口,从而降低客户代码与被调用对象的耦合关系,方便系统的维护与扩展。

interface Component 
{
    void Add(Component c);//添加树叶/树枝
    void Remove(Component c);//移除
    void Display(int depth);//打印/显示
}

/**
 * 枝节点
 */
class Composite implements Component
{
    private List<Component> children = new ArrayList<Component>();
    @Override
    public void Add(Component c) 
    {
        children.add(c);
    }
    @Override
    public void Remove(Component c) 
    {
        children.remove(c);
    }
    @Override
    public void Display(int depth) 
    {
        System.out.println("A"+depth);
        for ( Component c: children)
        {
            c.Display(depth+1);
        }
    }
}


/**
 * 叶节点
 */
class Leaf implements Component
{

    @Override
    public void Add(Component c) 
    {
        //叶节点无需增加分支和树叶,所以直接实现
        System.out.println("Cannot add to a leaf");
    }
    @Override
    public void Remove(Component c) 
    {
        System.out.println("Cannot remove to a leaf");
    }
    @Override
    public void Display(int depth) 
    {
         System.out.println("A"+depth);
    }
}
public class Demo 
{
    public static void main(String[] args) 
    {
        //根节点实例化
        Component  root= new Composite();
        //分枝X
        Composite  composite= new Composite();
        //分枝X上添加的叶子
        composite.Add(new Leaf());
        composite.Add(new Leaf());
        //添加到主根上
        root.Add(composite);
        //分枝Y
        Composite composite1 = new Composite();
        //添加Y到主根上
        root.Add(composite1);
        //分枝Y上添加的叶子
        composite1.Add(new Leaf());
        composite1.Add(new Leaf());
//        root.Remove(composite1);
        root.Display(1);
    }
}

组合模式分为:透明方式 和 安全方式
透明方式:(本文举例就属于透明方式)
在Component接口中声明用来管理子对象的方法中包含:add和remove。
优点:这样树枝树叶对于外界没有区别,具备完全一致的行为接口。
缺点:Leaf本身不具备add和remove方法的功能,实现也没有意义。

安全方式
在Component接口中不去声明add和remove方法,而是在Composite声明所用来管理子类对象的方法。
优点:Leaf无需实现add和remove方法。
缺点:由于不透明,树枝树叶 具备不同的接口,客户端调用的时候需要做相应的判断,带来了不便。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值