I have a Chequing account and a Saving account. I'm exploring how to implement the withdraw method using a Strategy pattern.
Currently, the Chequing and Saving account both inherit from Account. For Saving account, withdrawals should not cause the balance to dip below 100 dollars. With the Chequing account, withdrawals must include a cheque number.
I'm not confident in using this approach because, as you'll see below, the "otherArguments" parameter is totally useless in one scenario. And the only reason I have it like this is to "show" the use of the strategy pattern.
(for those who are concerned, this is part of a school project, all the code below I wrote and I'm curious about if there is a better way to get it done).
Here's what I've done so far:
public abstract class Account
{
public double Balance{get; set;}
public WithdrawStrategy Withdrawer
{
get; set;
}
public abstract void withdraw(double currentBalance, double amount, object otherArguments);
}
public class Chequing: Account
{
public Chequing()
{
Withdrawer= new ChequingAccountWithdrawer();
}
public override void withdraw(double currentBalance, double amount, object otherArguments)
{
if (null != Withdrawer)
{
double balance = Withdrawer.withdraw(currentBalance, amount, otherArguments);
Balance = balance;
}
}
}
public class Saving: Account
{
public Saving()
{
Withdrawer= new SavingAccountWithdrawer();
}
public override void withdraw(double currentBalance, double amount, object otherArguments)
{
if (null != Withdrawer)
{
double balance = Withdrawer.withdraw(currentBalance, amount, otherArguments);
Balance = balance;
}
}
}
public interface WithdrawStrategy
{
double withdraw(double currentBalance, double amount, object otherArguments);
}
public ChequingAccountWithdrawer: WithdrawStrategy
{
public double withdraw(double currentBalance, double amount, object otherArguments)
{
string cheqNum = otherArguments.ToString();
if (!string.IsNullOrEmpty(cheqNum))
{
currentBalance -= amount;
}
return currentBalance;
}
}
public SavingAccountWithdrawer: WithdrawStrategy
{
public double withdraw(double currentBalance, double amount, object otherArguments)
{
if (currentBalance - amount > 100) //hard code for example's sake
{
currentBalance -= amount;
}
return currentBalance;
}
}