经过好玩又有趣的软考备战和考试之后,终究还是要归于平静的.我们要学得东西还有很多,于是在软考结束的第二天,机房合作就马上提上了议事日程.在刚开始的时候,是一边做着新闻发布系统,一边思考合作的事宜,到了后来,逐步的过渡全身心投入机房合作的项目中去的阶段,因为我是项目组长,必须要做很多的工作,从一开始的建模到文档编写,再到敲代码,都要涉及,今天我们来讨论讨论如何在机房收费系统的费用计算上使用职责链模式.
首先我们要给出解决方案的类图
职责链模式无非就是把所有的处理对象,通过SetSuccessor()函数链接起来,形成一个处理链,当我们将一个问题请求出入时,该请求会沿着职责链进行传递,知道被处理为止.这就是职责链模式的工作流程.
下面我给出机房收费系统关于下机时给出的消费时间,如何计算应收费用的逻辑图
针对此设计给出一个使用C#编写的简单demo如下:
<span style="font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test { class Program { static void Main(string[] args) { ConcreteHandler1 handler1= new ConcreteHandler1 ("处理对象1"); ConcreteHandler2 handler2= new ConcreteHandler2 ("处理对象2"); ConcreteHandler3 handler3= new ConcreteHandler3 ("处理对象3"); handler1.SetSuperior(handler2); handler2.SetSuperior(handler3); Request request = new Request(); request.ConsumeTime = 4; handler1.RequestApplications(request); Request request1 = new Request(); request1.ConsumeTime = 20; handler1.RequestApplications(request1); Request request2 = new Request(); request2.ConsumeTime = 50; handler1.RequestApplications(request2); Console.Read(); } } //待处理的对象,即上网时间 class Request { //客户消费时间 private int consumetime; public int ConsumeTime { get { return consumetime; } set { consumetime = value; } } //客户消费金额 private double consumecash; public double ConsumeCash { get { return consumecash; } set { consumecash = value ; } } } //处理者抽象类 abstract class Handler { protected string name; protected Handler superior; public Handler(string name) { this.name = name; } public void SetSuperior(Handler superior) { this.superior = superior; } abstract public void RequestApplications(Request request); } //处理类1 class ConcreteHandler1:Handler { public ConcreteHandler1(string name) : base(name) { } public override void RequestApplications(Request request) { if (request .ConsumeTime <=5 ) { request.ConsumeCash = 0.0; Console.WriteLine("该客户的消费金额为{0}元,业务员:{1}", request .ConsumeCash ,name ); } else { if (superior != null) superior.RequestApplications(request); } } } //处理类2 class ConcreteHandler2:Handler { public ConcreteHandler2(string name) : base(name) { } public override void RequestApplications(Request request) { if (request .ConsumeTime >5 &&request .ConsumeTime <=30 ) { request.ConsumeCash = 3.0 * (30.0 / 60.0); Console.WriteLine("该客户的消费金额为{0}元,业务员:{1}",request .ConsumeCash,name ); } else { if (superior != null) superior.RequestApplications(request); } } } //处理类3 class ConcreteHandler3:Handler { public ConcreteHandler3(string name) : base(name) { } public override void RequestApplications(Request request) { if (request.ConsumeTime >30 ) { request.ConsumeCash = 3.0 * ((double )request .ConsumeTime / 60.0); Console.WriteLine("该客户的消费金额为{0}元,业务员:{1}", request .ConsumeCash,name ); } } } }</span>
运行结果如下
有的人可能觉得职责链模式用在此处显得有些多此一举,这样想不无道理,我们在机房收费系统尽量加入设计模式,目的是学习并且对设计模式进行实践,并不是要给出问题的完美解决方案,因此用的合不合适也就无所谓了,重要的是这学习的过程.