【发布时间】:2019-11-24 13:45:49
【问题描述】:
- 帐户可能有多种状态,例如 Frozen、Active、NotVerified、Closed。
- 账户可以执行以下操作:Deposit()、Withdraw()、HolderVerified()、Close()、Freeze()
- 这些操作的这些实施可能会因帐户的当前状态而异。
以下是我处理上述情况的方法。 但是,如果我们遇到必须这样做的情况怎么办:
账户当前状态为冻结状态下入金,扣10%的入金?
帐户
class Account
{
public decimal Balance { get; private set; }
private IAccountState State { get; set; }
public Account(Action onUnfreeze)
{
this.State = new NotVerified(onUnfreeze);
}
public void Deposit(decimal amount)
{
this.State = this.State.Deposit(() => { this.Balance += amount; });
}
public void Withdraw(decimal amount)
{
this.State = this.State.Withdraw(() => { this.Balance -= amount; });
}
public void HolderVerified()
{
this.State = this.State.HolderVerified();
}
public void Close()
{
this.State = this.State.Close();
}
public void Freeze()
{
this.State = this.State.Freeze();
}
}
IAccountState
interface IAccountState
{
IAccountState Deposit(Action addToBalance);
IAccountState Withdraw(Action substractFromBalance);
IAccountState Freeze();
IAccountState HolderVerified();
IAccountState Close();
}
IAccountState的具体实现
活动中
class Active : IAccountState
{
private Action OnUnfreeze { get; }
public Active(Action onUnfreeze)
{
OnUnfreeze = onUnfreeze;
}
public IAccountState Deposit(Action addToBalance)
{
addToBalance();
return this;
}
public IAccountState Withdraw(Action substractFromBalance)
{
substractFromBalance();
return this;
}
public IAccountState HolderVerified() => this;
public IAccountState Freeze() => new Frozen(this.OnUnfreeze);
public IAccountState Close() => new Closed();
}
未验证
class NotVerified : IAccountState
{
public Action OnUnfreeze { get; }
public NotVerified(Action onUnfreeze)
{
this.OnUnfreeze = onUnfreeze;
}
public IAccountState Close() => new Closed();
public IAccountState Deposit(Action addToBalance)
{
addToBalance();
return this;
}
public IAccountState Freeze() => this;
public IAccountState HolderVerified() => new Active(this.OnUnfreeze);
public IAccountState Withdraw(Action substractFromBalance) => this;
}
账户当前状态为冻结状态,需要扣除10%的押金,您将如何处理?
我不确定如何修改 NotVerified 类中的 Deposit 方法以满足要求:
public IAccountState Deposit(Action addToBalance)
{
addToBalance();
return this;
}
【问题讨论】:
标签: c# .net oop design-patterns object-oriented-analysis