COMPOSITE(组合模式)

来源:互联网 发布:河南千百知有限公司 编辑:程序博客网 时间:2024/06/09 20:59
1. 意图
将对象组合成树形结构以表示“部分 -整体”的层次结构。Composite使得用户对单个对象

和组合对象的使用具有一致性。

2. 适用性
以下情况使用Composite模式:
• 你想表示对象的部分-整体层次结构。
• 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。

3. 结构


典型的Composite对象结构如下图所示。


4. 参与者
• Component (Graphic)
— 为组合中的对象声明接口。
— 在适当的情况下,实现所有类共有接口的缺省行为。
— 声明一个接口用于访问和管理Component的子组件。
—(可选)在递归结构中定义一个接口,用于访问一个父部件,并在合适的情况下实现它。
• Leaf 
— 在组合中表示叶节点对象,叶节点没有子节点。
— 在组合中定义图元对象的行为。
• Composite (Picture)
— 定义有子部件的那些部件的行为。
— 存储子部件。
— 在Component接口中实现与子部件有关的操作。
• Client
— 通过Component接口操纵组合部件的对象。

5.代码实现


Component

public abstract class Component{    protected string name;    public Component(string name) {        this.name = name;    }    public abstract void Add(Component c);    public abstract void Remove(Component c);    public abstract void Display(int depth);}

Composite

public class Composite : Component{    private List<Component> children = new List<Component>();    public Composite(string name) : base(name)    {    }    public override void Add(Component c)    {        children.Add(c);    }    public override void Remove(Component c)    {        children.Remove(c);    }    public override void Display(int depth)    {        Debug.Log(new String('-', depth) + name);        foreach (Component component in children) {            component.Display(depth+2);        }    }}

Leaf

public class Leaf : Component{    public Leaf(string name) : base(name)    {    }    public override void Add(Component c)    {            }    public override void Remove(Component c)    {            }    public override void Display(int depth)    {        Debug.Log(new String('-',depth)+name);    }}

TestClient

public class TestClient : MonoBehaviour {    public void Test() {        //生成树根root,根上长出两叶LeafA和LeafB        Composite root = new Composite("root");        root.Add(new Leaf("Leaf A"));        root.Add(new Leaf("Leaf B"));        //跟上长出分支Composite X,分支上也有两叶LeafXA和LeafXB        Composite comp = new Composite("Composite X");        comp.Add(new Leaf("Leaf XA"));        comp.Add(new Leaf("Leaf XB"));        root.Add(comp);        //在Composite X上再长出分支Composite XY,分支上也有两叶LeafXYA和LeafXYB        Composite comp2 = new Composite("Composite XY");        comp2.Add(new Leaf("Leaf XYA"));        comp2.Add(new Leaf("Leaf XYB"));        comp.Add(comp2);        //根部又长出两叶LeafC和LeafD,可惜LeafD没长牢,被风走了        root.Add(new Leaf("Leaf C"));        Leaf leaf = new Leaf("Leaf D");        root.Add(leaf);        root.Remove(leaf);        //显示大树的样子        root.Display(1);    }}

输出结果

















0 0
原创粉丝点击