| 设计模式 | 定义 | 案例 |
| 责任链模式 | 问题 传给 多个可处理人 这多个处理人做成一个链表 | 学生请假条审核 上课老师(3天权限) 班主任 (5天权限) 校长 (30天权限) |
| 问题堆积在哪里 | 解决办法 | 进一步优化 |
| 学生需要找多个老师批准 太麻烦 | 学生只找当前上课老师 (可以批假人做出一个成链表) 如果当前上课老师不能批准找上级 流程: 学生-找->上课老师->班主任->校长 | 设计需要有前瞻性 流程灵活DIY 1 老师基类添加设置上级单位,灵活配置上级 2 老师单位做成工厂模式 |
AbstractTeacher: 抽象类
CurrentTeacher: 上课老师
ClassTeacher: 班主任
Headmaster: 校长
StudentContext:请假条

-
- public abstract class AbstractTeacher
- {
- // 灵活可变审核顺序
- protected AbstractTeacher next;
-
- // 设置上级
- public void SetNextAuditPeople(AbstractTeacher next)
- {
- this.next = next;
- }
-
- // 审核
- public abstract void Audit(StudentContext context);
-
- }
- using UnityEngine;
-
- public class CurrentTeacher : AbstractTeacher
- {
- // 时间
- int maxDate = 3;
- // 姓名
- string name = "当前上课老师";
-
- public override void Audit(StudentContext context)
- {
- // 是否通过
- if (context.GetDate() <= maxDate)
- {
- context.isOK = true;
- Debug.Log(name + ":批准.");
- }
- else
- {
- Debug.Log(name + ":无权限.");
- }
-
- // 没有通过:传给上级
- if (context.isOK != true)
- {
- if (null != next)
- next.Audit(context);
- else
- Debug.Log("没有上级联系人!");
- }
- }
- }
- using UnityEngine;
-
- public class ClassTeacher : AbstractTeacher
- {
- // 时间
- int maxDate = 14;
- // 姓名
- string name = "班主任";
-
- public override void Audit(StudentContext context)
- {
- // 是否通过
- if (context.GetDate() <= maxDate)
- {
- context.isOK = true;
- Debug.Log(name + ":批准.");
-
- }
- else
- {
- Debug.Log(name + ":无权限.");
- }
-
- // 没有通过:传给上级
- if (context.isOK != true)
- {
- if (null != next)
- next.Audit(context);
- else
- Debug.Log("没有上级联系人!");
- }
- }
- }
- using UnityEngine;
-
- public class Headmaster : AbstractTeacher
- {
- // 时间
- int maxDate = 30;
- // 姓名
- string name = "校长";
-
- public override void Audit(StudentContext context)
- {
- // 是否通过
- if (context.GetDate() <= maxDate)
- {
- context.isOK = true;
- Debug.Log(name + ":批准.");
- }
- else
- {
- Debug.Log(name + ":无权限.");
- }
-
- // 没有通过:传给上级
- if (context.isOK != true)
- {
- if (null != next)
- next.Audit(context);
- else
- Debug.Log("没有上级联系人!");
- }
- }
-
- }
- using UnityEngine;
-
- public class StudentContext
- {
- public bool isOK = false;
-
- string name = "学生A";
- int date = 0;
-
- private StudentContext(){}
-
- public StudentContext(string name, int date)
- {
- this.name = name;
- this.date = date;
- }
-
- public int GetDate()
- {
- return date;
- }
- }
- // 运行
- void Start()
- {
- // 请假条
- StudentContext sc = new StudentContext("小强", 29);
-
- // 老师
- AbstractTeacher teacher1 = new CurrentTeacher();
- AbstractTeacher teacher2 = new ClassTeacher();
- AbstractTeacher teacher3 = new Headmaster();
- // 设计上级
- {
- teacher1.SetNextAuditPeople(teacher2);
- teacher2.SetNextAuditPeople(teacher3);
- }
-
- // 请假
- teacher1.Audit(sc);
- }
