我正在使用.NET
框架练习编程,我对Singleton pattern
和State pattern
感到困惑。我尝试使用单例模式,现在我如何将状态模式实现到同一个类。我的代码是BankAccount
,它具有自动实现的属性,即AccountStateID
public class BronzeState : AccountStates
{
//static member
private static BronzeState bronzeState;
//constructor
private BronzeState()
{
this.LowerLimit = 0;
this.UpperLimit = 5000;
this.Rate = 0.01 / 100;
}
public static BronzeState GetInstance()
{
if (bronzeState != null)
return bronzeState;
else
{
bronzeState = new BronzeState();
return bronzeState;
}
}
public void StateChangeCheck(BankAccount bankAccount)
{
if (bankAccount.Balance > UpperLimit)
{
bankAccount.AccountState = new SilverState();
}
}
}
//same goes with GoldSte , SilverState, PlatinumState.
我唯一的问题是如果余额超过上限,我如何使用状态模式来改变状态。
答案 0 :(得分:1)
如果从AccountState
继承的所有类都是单例,那么您是否在询问如何将BankAccount
类的AccountStates
属性设置为其他状态?如果是,您使用了与上述相同的模式,那么:
public void StateChangeCheck(BankAccount bankAccount)
{
if (bankAccount.Balance > UpperLimit)
{
bankAccount.AccountState = SilverState.GetInstance();
}
}
另外,如果您有兴趣了解有关单例的线程安全实例化的更多信息,请查看MSDN