组合模式
定义:组合模式(又为 ‘整体-部分’ 模式)屏蔽了容器对象与单个对象在使用时的差异,为客户端提供统一的操作接口,从而降低客户代码与被调用对象的耦合关系,方便系统的维护与扩展。
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方法。
缺点:由于不透明,树枝 和 树叶 具备不同的接口,客户端调用的时候需要做相应的判断,带来了不便。
来源:CSDN
作者:S_simple_
链接:https://blog.csdn.net/S_simple_/article/details/103122237