1 |
package com.instantiations.example.money; |
2 |
|
3 |
/** |
4 |
* A simple Money. |
5 |
*/ |
6 |
public class Money implements IMoney { |
7 |
|
8 |
private int fAmount; |
9 |
private String fCurrency; |
10 |
|
11 |
/** |
12 |
* Constructs a money from the given amount and currency. |
13 |
*/ |
14 |
public Money(int amount, String currency) { |
15 |
fAmount= amount; |
16 |
fCurrency= currency; |
17 |
} |
18 |
/** |
19 |
* Adds a money to this money. Forwards the request to the addMoney helper. |
20 |
*/ |
21 |
public IMoney add(IMoney m) { |
22 |
return m.addMoney(this); |
23 |
} |
24 |
public IMoney addMoney(Money m) { |
25 |
if (m.currency().equals(currency()) ) |
26 |
return new Money(amount()+m.amount(), currency()); |
27 |
return MoneyBag.create(this, m); |
28 |
} |
29 |
public IMoney addMoneyBag(MoneyBag s) { |
30 |
return s.addMoney(this); |
31 |
} |
32 |
public int amount() { |
33 |
return fAmount; |
34 |
} |
35 |
public String currency() { |
36 |
return fCurrency; |
37 |
} |
38 |
public boolean equals(Object anObject) { |
39 |
if (isZero()) |
40 |
if (anObject instanceof IMoney) |
41 |
return ((IMoney)anObject).isZero(); |
42 |
if (anObject instanceof Money) { |
43 |
Money aMoney= (Money)anObject; |
44 |
return aMoney.currency().equals(currency()) |
45 |
&& amount() == aMoney.amount(); |
46 |
} |
47 |
return false; |
48 |
} |
49 |
public int hashCode() { |
50 |
return fCurrency.hashCode()+fAmount; |
51 |
} |
52 |
public boolean isZero() { |
53 |
return amount() == 0; |
54 |
} |
55 |
public IMoney multiply(int factor) { |
56 |
return new Money(amount()*factor, currency()); |
57 |
} |
58 |
public IMoney negate() { |
59 |
return new Money(-amount(), currency()); |
60 |
} |
61 |
public IMoney subtract(IMoney m) { |
62 |
return add(m.negate()); |
63 |
} |
64 |
public String toString() { |
65 |
StringBuffer buffer = new StringBuffer(); |
66 |
buffer.append("["+amount()+" "+currency()+"]"); |
67 |
return buffer.toString(); |
68 |
} |
69 |
public /*this makes no sense*/ void appendTo(MoneyBag m) { |
70 |
m.appendMoney(this); |
71 |
} |
72 |
} |