using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { class Program { //责任链模式指的是——某个请求需要多个对象进行处理, //从而避免请求的发送者和接收之间的耦合关系。 //将这些对象连成一条链子,并沿着这条链子传递该请求,直到有对象处理它为止。 static void Main(string[] args) { PurchaseRequest requestTelphone = new PurchaseRequest(4000.0, "电话"); PurchaseRequest requestSoftware = new PurchaseRequest(10000.0, "软件"); PurchaseRequest requestComputers = new PurchaseRequest(40000.0, "电脑"); PurchaseRequest requestCar = new PurchaseRequest(140000.0, "汽车"); Approver manager = new Manager("经理"); Approver Vp = new VicePresident("副总"); Approver Pre = new President("老板"); // 设置责任链 manager.NextApprover = Vp; Vp.NextApprover = Pre; // 处理请求 manager.ProcessRequest(requestTelphone); manager.ProcessRequest(requestSoftware); manager.ProcessRequest(requestComputers); manager.ProcessRequest(requestCar); Console.ReadLine(); } // 采购请求 public class PurchaseRequest { // 金额 public double Amount { get; set; } // 产品名字 public string ProductName { get; set; } public PurchaseRequest(double amount, string productName) { Amount = amount; ProductName = productName; } } // 审批人,Handler public abstract class Approver { public Approver NextApprover { get; set; } public string Name { get; set; } public Approver(string name) { this.Name = name; } public abstract void ProcessRequest(PurchaseRequest request); } // ConcreteHandler,经理 public class Manager : Approver { public Manager(string name) : base(name) {} //少于10000块,可以决定 public override void ProcessRequest(PurchaseRequest request) { if (request.Amount < 10000.0) { Console.WriteLine("{0}:{1}少于10000块,{2}可以批准!", request.ProductName, request.Amount,Name); } else if (NextApprover != null) { NextApprover.ProcessRequest(request); } } } // ConcreteHandler,副总 public class VicePresident : Approver { public VicePresident(string name) : base(name) {} //少于25000块,可以决定 public override void ProcessRequest(PurchaseRequest request) { if (request.Amount < 25000.0) { Console.WriteLine("{0}:{1}少于10000块,{2}可以批准!", request.ProductName, request.Amount, Name); } else if (NextApprover != null) { NextApprover.ProcessRequest(request); } } } // ConcreteHandler,总经理 public class President : Approver { public President(string name) : base(name) {} //少于100000可以决定 public override void ProcessRequest(PurchaseRequest request) { if (request.Amount < 100000.0) { Console.WriteLine("{0}:{1}少于10000块,{2}可以批准!", request.ProductName, request.Amount, Name); } else { Console.WriteLine("需要组织一个会议讨论"); } } } } }
时间: 2024-10-29 02:30:35