【Unity3D与23种设计模式】组合模式(Composite)

时间:2021-09-15 13:15:37

前段时间在忙一个新项目

博客好久没有更新了

GoF中定义:

“将对象以树状结构组合,用以表现部分-全体的层次关系。组合模式让客户端在操作各个对象或组合时是一致的。”

是一致的意思就是:能够对根节点调用的操作,同样能够在叶节点上使用

“分层式管理结构”一般也称为“树状结构”

Unity中对于游戏对象的管理,也应用了树形结构的概念

让游戏对象之间可以被当成子对象或设置为父对象的方式来连接两个对象

public abstract class IComponent {
protected string m_Value; public abstract void Operation(); public virtual void Add(IComponent theComponent) {}
public virtual void Remove(IComponent theComponent) { }
public virtual IComponent GetChild(int index) {
return null;
}
}
//节点类
public class Composite : IComponent {
List<IComponent> m_Childs = new List<IComponent>(); public Composite(string Value) {
m_Value = Value;
} public override void Operation()
{
foreach (IComponent theComponent in m_Childs) {
theComponent.Operation();
}
} public override void Add(IComponent theComponent)
{
m_Childs.Add(theComponent);
} public override void Remove(IComponent theComponent)
{
m_Childs.Remove(theComponent);
} public override IComponent GetChild(int index)
{
return m_Childs[index];
}
}
//叶子类
public class Leaf : IComponent {
public Leaf(string Value) {
m_Value = Value;
} public override void Operation(){}
}
//测试类
public class TestComposite {
void UnitTest() {
IComponent theRoot = new Composite("Root"); theRoot.Add(new Leaf("Leaf1"));
theRoot.Add(new Leaf("Leaf2")); IComponent theChild1 = new Composite("Child1");
theChild1.Add(new Leaf("Child1.Leaf1"));
theChild1.Add(new Leaf("Child1.Leaf2"));
theRoot.Add(theChild1); IComponent theChild2 = new Composite("Child2");
theChild2.Add(new Leaf("Child2.Leaf1"));
theChild2.Add(new Leaf("Child2.Leaf2"));
theChild2.Add(new Leaf("Child2.Leaf3"));
theRoot.Add(theChild2); theRoot.Operation();
}
}

组合模式优点:

界面与功能分离

工作切分更容易

界面更改不影响项目

缺点:

组件名称重复

组件更名不易

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著