Unity 设计模式之 组合模式的实例介绍
1、组合模式:
将对象组合成属性结构以表示 部分-整体 的层次结构关系。组合模式使得用户对单个对象和组合对象的使用具有一致性。

2、模式中的角色:
1)Component(组件类):组合中的对象声明接口,在适当的时候,实现所有类的公共接口的默认行为。声明一个接口用于访问和管理 Component 的子部件;
2)Composite(组合类):定义枝节点行为,用来存储子部件,在 Component 接口中实现与子部件有关的操作,比如增加 Add 和删除 Remove等;
3)Leaf(叶子类):在组合中表示叶子节点对象,叶节点没有子节点;
3、组合模式的使用实例:

1、打开Unity,新建一个空工程,具体如下图

2、在工程中,新建几个脚本,然后双击打开,具体如下图

3、脚本的具体代码和代码说明如下图




4、CompanyComponent 脚本具体内容如下:
public abstract class CompanyComponent {
protected string name;
public CompanyComponent(string name){
this.name = name;
}
public abstract void Add (CompanyComponent company);
public abstract void Remove (CompanyComponent company);
public abstract void Display (int depth);
public abstract void LineOfDuty ();
}
5、ConcreteCompanyComposite 脚本具体内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ConcreteCompanyComposite : CompanyComponent {
private List<CompanyComponent> children = new List<CompanyComponent>();
public ConcreteCompanyComposite(string name): base(name){
}
public override void Add (CompanyComponent company)
{
children.Add (company);
}
public override void Remove (CompanyComponent company)
{
children.Remove (company);
}
public override void Display (int depth)
{
Debug.Log (new String('-', depth) + name);
foreach(CompanyComponent component in children){
component.Display (depth +2);
}
}
public override void LineOfDuty ()
{
foreach(CompanyComponent component in children){
component.LineOfDuty ();
}
}
}
6、HRDepartmntLeaf 脚本具体内容如下:
using UnityEngine;
using System;
public class HRDepartmntLeaf : CompanyComponent {
public HRDepartmntLeaf(string name): base(name){
}
public override void Add (CompanyComponent company)
{
}
public override void Remove (CompanyComponent company)
{
}
public override void Display (int depth)
{
Debug.Log (new String('-', depth) + name);
}
public override void LineOfDuty ()
{
Debug.Log (name + " 员工招聘培训管理");
}
}
7、Test 脚本具体内容如下:
using UnityEngine;
public class Test : MonoBehaviour {
// Use this for initialization
void Start () {
ConcreteCompanyComposite root = new ConcreteCompanyComposite ("总公司");
root.Add (new HRDepartmntLeaf("总公司人力资源部"));
ConcreteCompanyComposite company1 = new ConcreteCompanyComposite ("分公司1");
company1.Add (new HRDepartmntLeaf("分公司1人力资源部"));
root.Add (company1);
ConcreteCompanyComposite company2 = new ConcreteCompanyComposite ("分公司2");
company2.Add (new HRDepartmntLeaf("分公司2人力资源部"));
root.Add (company2);
ConcreteCompanyComposite company3 = new ConcreteCompanyComposite ("分公司3");
company3.Add (new HRDepartmntLeaf("分公司3人力资源部"));
company2.Add (company3);
Debug.Log ("\n 公司结构图");
root.Display (1);
Debug.Log ("\n 公司职责");
root.LineOfDuty ();
}
}
8、脚本编译正确,回到Unity界面,在场景中新建一个 GameObject,并把 Test 脚本赋给 GameObject,具体如下图

9、运行场景,控制台 Console 打印如下图

10、到此,《Unity 设计模式之 组合模式的实例介绍》讲解结束,谢谢