-
Notifications
You must be signed in to change notification settings - Fork 1
/
3-1-chain-of-responsability.vala
69 lines (57 loc) · 1.58 KB
/
3-1-chain-of-responsability.vala
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
public errordomain OurError {
PAY_ERROR
}
abstract class Account : Object {
protected Account? successor = null;
protected float balance;
public void set_next (Account account) {
successor = account;
}
public void pay (float ammount_to_pay) throws OurError {
if (can_pay (ammount_to_pay)) {
print ("Paid %f using %s\n", ammount_to_pay, get_type ().name ());
} else if (successor != null) {
print ("Cannot pay using %s, Proceeding ..\n", get_type ().name ());
successor.pay (ammount_to_pay);
} else {
throw new OurError.PAY_ERROR ("None of the accounts have enough balance");
}
}
public bool can_pay (float ammount) {
return balance >= ammount;
}
}
class Bank : Account {
public Bank (float balance) {
this.balance = balance;
}
}
class Paypal : Account {
public Paypal (float balance) {
this.balance = balance;
}
}
class Bitcoin : Account {
public Bitcoin (float balance) {
this.balance = balance;
}
}
public int 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);
var paypal = new Paypal (200);
var bitcoin = new Bitcoin (300);
bank.set_next (paypal);
paypal.set_next (bitcoin);
try {
bank.pay (259);
} catch (OurError e) {
stderr.printf ("%s\n", e.message);
}
return 0;
}