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#程序设计有所帮助。
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话