我有一个支票账户和一个储蓄账户。我正在探索如何使用 Strategy 模式来实现withdraw 方法。
目前,Checking 和 Saving 账户都继承自 Account。对于储蓄账户,提款不应导致余额低于 100 美元。使用支票账户,提款必须包含支票号码。
我对使用这种方法没有信心,因为正如您将在下面看到的那样,“otherArguments”参数在一种情况下完全没用。我拥有它的唯一原因是“展示”策略模式的使用。
(对于那些担心的人,这是学校项目的一部分,下面的所有代码都是我编写的,我很好奇是否有更好的方法来完成它)。
这是我到目前为止所做的:
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;
}
}