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