LindDotNetCore~職責鏈模式(shi)的應用
職責鏈模式
它是一種設計模塊,主要將操作流程與具體操作解耦,讓每個操作都可以設置自己的操作流程,這對于工作流應用是一個不錯的選擇!
下(xia)面是官(guan)方標準(zhun)的(de)定(ding)義(yi):責(ze)任鏈(lian)模(mo)式是一(yi)(yi)種設(she)計模(mo)式。在責(ze)任鏈(lian)模(mo)式里,很多對象(xiang)由(you)每(mei)一(yi)(yi)個(ge)(ge)對象(xiang)對其下(xia)家的(de)引用而連(lian)接起來形成(cheng)一(yi)(yi)條鏈(lian)。請(qing)求(qiu)在這(zhe)(zhe)(zhe)個(ge)(ge)鏈(lian)上傳遞(di),直到鏈(lian)上的(de)某一(yi)(yi)個(ge)(ge)對象(xiang)決定(ding)處理(li)此請(qing)求(qiu)。發出這(zhe)(zhe)(zhe)個(ge)(ge)請(qing)求(qiu)的(de)客戶端(duan)并不知道鏈(lian)上的(de)哪一(yi)(yi)個(ge)(ge)對象(xiang)最終處理(li)這(zhe)(zhe)(zhe)個(ge)(ge)請(qing)求(qiu),這(zhe)(zhe)(zhe)使得系(xi)統可(ke)以在不影(ying)響客戶端(duan)的(de)情況下(xia)動態(tai)地重新組織和分配責(ze)任。
職責鏈模式組成
- 三大對象
- 命令處理
- 處理流程
- 命令上下文
- 命令只負責組織各個流程的次序,對流程實現細節沒興趣
- 具體流程只實現自己關注的代碼,對下一個流程未知
在具體代碼中的體現
抽象命令
public interface ICommand
{
void Execute(CommandParameters parameters);
}
抽象流程
/// <summary>
/// 工作流-抽象處理者
/// </summary>
public abstract class WorkFlow
{
protected WorkFlow Next; // 定義后繼對象
protected object SharedObj; // 共享對象
// 設置后繼者
public WorkFlow SetNext(WorkFlow next)
{
Next = next;
return next;
}
// 抽象請求處理方法
public virtual void ProcessRequest(CommandParameters command)
{
if (Next != null)
Next.ProcessRequest(command);
}
}
命令需(xu)要(yao)把(ba)參數傳(chuan)遞給每個工(gong)作流程
public class CommandParameters
{
public string CommandType { get; set; }
public string JsonObj { get; set; }
public CommandParameters(string type, string jsonObj)
{
CommandType = type;
JsonObj = jsonObj;
}
}
下面看(kan)一個職責鏈(lian)模式里(li)的具體命(ming)令(ling)和(he)具體流程(步(bu)驟),每個步(bu)驟可以設置它下一步(bu)是什么
public class CommandInsert : ICommand
{
public void Execute(CommandParameters parameters)
{
WorkFlow workFlow = new WorkFlow_InsertLogger();
workFlow.SetNext(new WorkFlow_InsertAudit());
workFlow.ProcessRequest(parameters);
}
}
public class CommandUpdate : ICommand
{
public void Execute(CommandParameters parameters)
{
WorkFlow workFlow = new WorkFlow_InsertAudit();
workFlow.SetNext(new WorkFlow_InsertLogger());
workFlow.ProcessRequest(parameters);
}
}
public class WorkFlow_InsertLogger : WorkFlow
{
public override void ProcessRequest(CommandParameters command)
{
System.Console.WriteLine("WorkFlow1");
ProcessRequest(command);
}
}
public class WorkFlow_InsertAudit : WorkFlow
{
public override void ProcessRequest(CommandParameters command)
{
System.Console.WriteLine("WorkFlow2");
ProcessRequest(command);
}
}
public class ChainResponsibility
{
[Fact]
public void Test1()
{
var command = new CommandInsert();
command.Execute(new CommandParameters("test", "OK"));
}
[Fact]
public void Test2()
{
var command = new CommandUpdate();
command.Execute(new CommandParameters("test", "OK"));
}
}
待續……
回到目錄