组合模式

组合模式实现的是一种树形结构。
在这里插入图片描述

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();
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值