C#职责链模式实例详解
本文实例讲述了C#职责链模式。分享给大家供大家参考。具体如下:
ConcreteHandler1.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceConsoleApplication1 { publicclassConcreteHandler1:Handler { publicoverridevoidHandRequest(intrequest) { if(request>0&&request<10) { Console.WriteLine("{0}处理请求{1}",this.GetType().Name,request); } elseif(successor!=null) { successor.HandRequest(request); } } } }
ConcreteHandler2.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceConsoleApplication1 { publicclassConcreteHandler2:Handler { publicoverridevoidHandRequest(intrequest) { if(request>10&&request<20) { Console.WriteLine("{0}处理请求{1}",this.GetType().Name,request); } elseif(successor!=null) { successor.HandRequest(request); } } } }
ConcreteHandler3.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceConsoleApplication1 { publicclassConcreteHandler3:Handler { publicoverridevoidHandRequest(intrequest) { if(request>20&&request<30) { Console.WriteLine("{0}处理请求{1}",this.GetType().Name,request); } elseif(successor!=null) { successor.HandRequest(request); } } } }
Handler.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceConsoleApplication1 { publicabstractclassHandler { protectedHandlersuccessor; publicvoidSetSuccessor(Handlersuccessor) { this.successor=successor; } publicabstractvoidHandRequest(intrequest); } }
Program.cs如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceConsoleApplication1 { classProgram { staticvoidMain(string[]args) { Handlerh1=newConcreteHandler1(); Handlerh2=newConcreteHandler2(); Handlerh3=newConcreteHandler3(); h1.SetSuccessor(h2); h2.SetSuccessor(h3); int[]requests={2,5,14,22,18,3,27,20}; foreach(intrequestinrequests) { h1.HandRequest(request); } Console.ReadKey(); } } }
希望本文所述对大家的C#程序设计有所帮助。