当座預金口座と普通預金口座を持っています。戦略パターンを使用して撤回メソッドを実装する方法を検討しています。
現在、当座預金口座と普通預金口座はどちらも Account を継承しています。普通預金口座の場合、引き出しによって残高が 100 ドルを下回ってはなりません。当座預金口座では、引き出しには小切手番号が含まれている必要があります。
以下に示すように、「otherArguments」パラメーターは 1 つのシナリオではまったく役に立たないため、このアプローチを使用する自信はありません。そして、私がこのようにした唯一の理由は、戦略パターンの使用を「示す」ことです。
(心配している人のために、これは学校のプロジェクトの一部であり、以下のコードはすべて私が書いたものであり、それを実現するためのより良い方法があるかどうか知りたいです).
これまでに行ったことは次のとおりです。
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;
}
}