summaryrefslogtreecommitdiff
path: root/DesignPatterns/src/app/DesignPatterns.Factory/Money.cs
diff options
context:
space:
mode:
Diffstat (limited to 'DesignPatterns/src/app/DesignPatterns.Factory/Money.cs')
-rw-r--r--DesignPatterns/src/app/DesignPatterns.Factory/Money.cs56
1 files changed, 56 insertions, 0 deletions
diff --git a/DesignPatterns/src/app/DesignPatterns.Factory/Money.cs b/DesignPatterns/src/app/DesignPatterns.Factory/Money.cs
new file mode 100644
index 0000000..956c9a6
--- /dev/null
+++ b/DesignPatterns/src/app/DesignPatterns.Factory/Money.cs
@@ -0,0 +1,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;
+ }
+} \ No newline at end of file