|
| 1 | +using System; |
| 2 | + |
| 3 | +namespace ChainOfResponsibilityPattern |
| 4 | +{ |
| 5 | + abstract class Account |
| 6 | + { |
| 7 | + private Account mSuccessor; |
| 8 | + protected decimal mBalance; |
| 9 | + |
| 10 | + public void SetNext(Account account) |
| 11 | + { |
| 12 | + mSuccessor = account; |
| 13 | + } |
| 14 | + |
| 15 | + public void Pay(decimal amountTopay) |
| 16 | + { |
| 17 | + if (CanPay(amountTopay)) |
| 18 | + { |
| 19 | + Console.WriteLine("Paid {0:c} using {1}.", amountTopay, this.GetType().Name); |
| 20 | + } |
| 21 | + else if (this.mSuccessor != null) |
| 22 | + { |
| 23 | + Console.WriteLine("Cannot pay using {0}. Proceeding..", this.GetType().Name); |
| 24 | + mSuccessor.Pay(amountTopay); |
| 25 | + } |
| 26 | + else |
| 27 | + { |
| 28 | + throw new Exception("None of the accounts have enough balance"); |
| 29 | + } |
| 30 | + } |
| 31 | + private bool CanPay(decimal amount) |
| 32 | + { |
| 33 | + return mBalance >= amount ? true : false; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + class Bank : Account |
| 38 | + { |
| 39 | + public Bank(decimal balance) |
| 40 | + { |
| 41 | + this.mBalance = balance; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + class Paypal : Account |
| 46 | + { |
| 47 | + public Paypal(decimal balance) |
| 48 | + { |
| 49 | + this.mBalance = balance; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + class Bitcoin : Account |
| 54 | + { |
| 55 | + public Bitcoin(decimal balance) |
| 56 | + { |
| 57 | + this.mBalance = balance; |
| 58 | + } |
| 59 | + } |
| 60 | + class Program |
| 61 | + { |
| 62 | + static void Main(string[] args) |
| 63 | + { |
| 64 | + // Let's prepare a chain like below |
| 65 | + // $bank->$paypal->$bitcoin |
| 66 | + // |
| 67 | + // First priority bank |
| 68 | + // If bank can't pay then paypal |
| 69 | + // If paypal can't pay then bit coin |
| 70 | + var bank = new Bank(100); // Bank with balance 100 |
| 71 | + var paypal = new Paypal(200); // Paypal with balance 200 |
| 72 | + var bitcoin = new Bitcoin(300); // Bitcoin with balance 300 |
| 73 | + |
| 74 | + bank.SetNext(paypal); |
| 75 | + paypal.SetNext(bitcoin); |
| 76 | + |
| 77 | + // Let's try to pay using the first priority i.e. bank |
| 78 | + bank.Pay(259); |
| 79 | + // Output will be |
| 80 | + // ============== |
| 81 | + // Cannot pay using bank. Proceeding .. |
| 82 | + // Cannot pay using paypal. Proceeding ..: |
| 83 | + // Paid 259 using Bitcoin! |
| 84 | + |
| 85 | + Console.ReadLine(); |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments