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; } }