Unity-责任链模式

思考并回答以下问题:

介绍

定义

使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。

组成部分

The classes and objects participating in this pattern are:

Handler (Approver)

defines an interface for handling the requests(optional) implements the successor link

ConcreteHandler (Director, VicePresident, President)

handles requests it is responsible for can access its successor if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor

Client (ChainApp)

initiates the request to a ConcreteHandler object on the chain

结构

ChainOfResponsibilityStructure.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using UnityEngine;
using System.Collections;

public class ChainOfResponsibilityStructure : MonoBehaviour
{
void Start()
{
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);

// Generate and process request
int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
foreach (int request in requests)
{
h1.HandleRequest(request);
}

}
}

/// <summary>
/// The 'Handler' abstract class
/// </summary>
abstract class Handler
{
protected Handler successor;

public void SetSuccessor(Handler successor)
{
this.successor = successor;
}

public abstract void HandleRequest(int request);
}

/// <summary>
/// The 'ConcreteHandler1' class
/// </summary>
class ConcreteHandler1 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 0 && request < 10)
{
Debug.Log(this.GetType().Name + " handled request " + request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}

/// <summary>
/// The 'ConcreteHandler2' class
/// </summary>
class ConcreteHandler2 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 10 && request < 20)
{
Debug.Log(this.GetType().Name + " handled request " + request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}

/// <summary>
/// The 'ConcreteHandler3' class
/// </summary>
class ConcreteHandler3 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 20 && request < 30)
{
Debug.Log(this.GetType().Name+" handled request "+request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}
0%