我如何在一个类中使用Singleton模式处理State Pattern

时间:2016-10-12 06:51:15

标签: c# asp.net singleton state

我正在使用.NET框架练习编程,我对Singleton patternState 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.

我唯一的问题是如果余额超过上限,我如何使用状态模式来改变状态。

1 个答案:

答案 0 :(得分:1)

如果从AccountState继承的所有类都是单例,那么您是否在询问如何将BankAccount类的AccountStates属性设置为其他状态?如果是,您使用了与上述相同的模式,那么:

public void StateChangeCheck(BankAccount bankAccount)
{
    if (bankAccount.Balance > UpperLimit)
    {
        bankAccount.AccountState = SilverState.GetInstance(); 
    }
}

另外,如果您有兴趣了解有关单例的线程安全实例化的更多信息,请查看MSDN