组合模式实现的是一种树形结构。
using System;
using System.Collections.Generic;
public abstract class Component
{
string _Name;
public Component(string name)
{
this._Name = name;
}
public string GetName()
{
return _Name;
}
public abstract void Operation();
public abstract void Add(Component c);
public abstract bool Remove(Component c);
public abstract Component GetChild(int i);
}
using System.Collections.Generic;
using UnityEngine;
//树是递归结构,其中只有两种结点:根节点和叶子结点
//根节点
public class Composite : Component
{
private List<Component> childs;
public Composite(string name):base(name)
{
childs = new List<Component>();
}
public override void Add(Component com)
{
childs.Add(com);
}
public override Component GetChild(int i)
{
if(i>=0&&i<childs.Count)
{
return childs[i];
}
Debug.LogError("没有这样的结点");
return null;
}
public override void Operation()
{
Debug.Log(GetName() + "在执行Operation()");
foreach (var item in childs)
{
item.Operation();
}
}
public override bool Remove(Component c)
{
return childs.Remove(c);
}
}
using System.Collections.Generic;
using UnityEngine;
//树是递归结构,其中只有两种结点:根节点和叶子结点
//根节点
public class Leaf : Component
{
public Leaf(string name) : base(name)
{
}
public override void Add(Component com)
{
Debug.LogError("不能再叶子结点添加子节点");
return;
}
public override Component GetChild(int i)
{
Debug.LogError("不能再叶子结点获得子节点");
return null;
}
public override void Operation()
{
Debug.Log(GetName() + "在执行Operation()");
}
public override bool Remove(Component c)
{
Debug.LogError("不能再叶子结点删除子节点");
return false;
}
}
Component theRoot = new Composite("Root");
theRoot.Add(new Leaf("Leaf1"));
theRoot.Add(new Leaf("Leaf2"));
Component theChild1 = new Composite("Child1");
theChild1.Add(new Leaf("Child1.Leaf1"));
theChild1.Add(new Leaf("Child1.Leaf2"));
theRoot.Add(theChild1);
Component theChild2 = new Composite("Child2");
theChild2.Add(new Leaf("Child2.Leaf1"));
theChild2.Add(new Leaf("Child2.Leaf2"));
theRoot.Add(theChild2);
theRoot.Operation();