blob: 956c9a62609233d5cae728ffa8c1374f262cdd69 (
plain)
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
|
using System;
namespace DesignPatterns.Factory {
public class Money : IMoney {
public Money( double amount ) : this( amount, Currency.Canadian ) {}
public Money( double amount, ICurrency currency ) {
if ( amount < 0 ) {
throw new NegativeMoneyException( );
}
_amount = amount;
_currency = currency;
}
public double Amount {
get { return _amount; }
}
public ICurrency TypeOfCurrency {
get { return _currency; }
}
public IMoney Add( IMoney other ) {
if ( other != null ) {
if ( other.TypeOfCurrency.Equals( TypeOfCurrency ) ) {
return new Money( other.Amount + Amount );
}
throw new CannotAddMoniesException( "Cannot add monies of different currency" );
}
return this;
}
public IMoney Subtract( IMoney money ) {
return ( money != null ) ? new Money( Amount - money.Amount ) : null;
}
public override bool Equals( object obj ) {
IMoney other = obj as Money;
if ( other != null ) {
return other.Amount == Amount;
}
return false;
}
public override int GetHashCode( ) {
return base.GetHashCode( ) + new Random( ( int )DateTime.Now.Ticks ).Next( );
}
public override string ToString( ) {
return _amount.ToString( "F" );
}
private readonly double _amount;
private readonly ICurrency _currency;
}
}
|