【責任鏈模式】這個設計模式貌似蠻好理解的,想象一下富土康三號流水線質檢員張全蛋~,一部IPhone要經過層層質檢,合格後方能出廠,每一道工序的質檢員都有一個編號,通過了就貼一個帶編號的質檢通過標籤,以後這塊出了問題,很容易就找到是誰質檢時候在划水。
貼代碼:(不好意思,這次質檢主機)
using UnityEngine;
/// <summary>
/// 設計模式——責任鏈模式
/// </summary>
public class DesignMode_Responsibility : MonoBehaviour {
// Use this for initialization
void Start () {
//質檢100臺電腦吧
for (int i = 0; i < 100; i++)
{
Computer computer = new Computer();
TestOne one = new TestOne();
one.TestComputer(computer);
}
}
}
/// <summary>
/// 一臺新主機出廠要經過3道質檢
/// </summary>
public class Computer
{
public bool isTestOne;
public bool isTestTwo;
public bool isTestThree;
public void NextTest(Test test)
{
test.TestComputer(this);
}
/// <summary>
/// 每臺電腦出廠前每道質檢都可能出問題,用隨機布爾值來標識是否通過某道質檢
/// </summary>
public Computer()
{
isTestOne = Random.value > 0.5f;
isTestTwo = Random.value > 0.5f;
isTestThree = Random.value > 0.5f;
}
}
/// <summary>
/// 質檢基類
/// </summary>
public abstract class Test
{
public abstract void TestComputer(Computer computer);
}
public class TestOne : Test
{
public override void TestComputer(Computer computer)
{
Debug.Log("1號質檢員對電腦進行質檢");
if (computer.isTestOne)
{
Debug.Log("1號質檢通過,送往2號質檢");
computer.NextTest(new TestTwo());
}
else
{
Debug.Log("1號質檢不通過,不可以出廠");
}
}
}
public class TestTwo : Test
{
public override void TestComputer(Computer computer)
{
Debug.Log("2號質檢員對電腦進行質檢");
if (computer.isTestOne)
{
Debug.Log("2號質檢通過,送往3號質檢");
computer.NextTest(new TestThree());
}
else
{
Debug.Log("2號質檢不通過,不可以出廠");
}
}
}
public class TestThree : Test
{
public override void TestComputer(Computer computer)
{
Debug.Log("3號質檢員對電腦進行質檢");
if (computer.isTestOne)
{
Debug.Log("3號質檢通過,可以出廠");
}
else
{
Debug.Log("3號質檢不通過,不可以出廠");
}
}
}
運行截圖(這個隨機結果還是比較均勻的):