职责链模式(Chain of Responsibility)
请假条件:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chain_of_Responsibility { class Program { //学生接口 public interface IStudent{ //获得学生请假级别:级别0:3小时内(纪委直接处理),级别1:超过3小时(由老师处理) int getLevel(); //获得学生请假消息 string getRequestMessage(); } //学生实现类 public class Student :IStudent { //请假级别 private int level=-1; //请假消息 private string message; public Student(int level, String message) { this.level = level; this.message=message; } public int getLevel() { return this.level; } public string getRequestMessage(){ return this.message; } } //抽象处理者接口 public interface IHandler { //处理请求 void handleRequest(IStudent student); //设置下一个处理着 void setHandler(IHandler handler); } //抽象处理者 public abstract class AbstractHandler : IHandler { //下一个处理者 private IHandler handler; //请假级别 private int level = -1; //设置级别 public AbstractHandler(int level) { this.level = level; } //处理请求,交由子类负责进行具体的处理 public abstract void process(IStudent student); public void handleRequest(IStudent student) { if (student != null) { if (this.level == student.getLevel()) { //如果请假级别和当前级别一致,则当前对象进行处理 this.process(student); } else { if (this.handler != null) { Console.WriteLine(student.getRequestMessage() + " 请求米老师处理!"); //如果当前对象处理不了,则交给下一个处理者进行处理 this.handler.handleRequest(student); } } } } //设置下一个处理者 public void setHandler(IHandler handler) { this.handler = handler; } } //纪委 public class DisciplineHandler : AbstractHandler { public DisciplineHandler():base(0){} public override void process(IStudent student) { Console.WriteLine("纪委 批复:" + student.getRequestMessage ()); } } //老师 public class TeacherHandler : AbstractHandler { public TeacherHandler() : base(1) { } public override void process(IStudent student) { Console.WriteLine("老师 批复:" + student.getRequestMessage()); } } //设置职责链关联 public class ProcessHandler { private IHandler disciplineHandler; private IHandler teacherHandler; //单例模式 private static ProcessHandler processHandler = new ProcessHandler(); private ProcessHandler() { this.disciplineHandler = new DisciplineHandler(); this.teacherHandler = new TeacherHandler(); this.disciplineHandler.setHandler(this.teacherHandler); } public static ProcessHandler getInstance() { return processHandler; } //发送请假请求 public void sendMessage(IStudent student) { this.disciplineHandler.handleRequest(student); } } static void Main(string[] args) { ProcessHandler processHandler = ProcessHandler.getInstance(); IStudent student0 = new Student(0, "学生张XX快递到了,要请假20分钟!"); IStudent student1 = new Student(1, "学生李XX运动时摔伤了腿,要请假一周!"); Console.WriteLine("************************************************************"); processHandler.sendMessage(student0); Console.WriteLine("************************************************************"); processHandler.sendMessage(student1); Console.WriteLine("************************************************************"); } } }
原文地址:http://blog.csdn.net/ry513705618/article/details/39458899