Nawzir Kadiwal
Nawzir Kadiwal

Reputation: 17

How can i tackle State Pattern with Singleton pattern in one class

I am practicing programming using .NET framework and I am really confused with Singleton pattern and State pattern. I tried working out with singleton pattern and now how can I implement State pattern to the same class. My code is BankAccount which has autoimplemented property i.e. 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.

My only question is how I can use state pattern to change state if balance is more that upper limit.

Upvotes: 0

Views: 560

Answers (1)

RVid
RVid

Reputation: 1287

Are you asking how to set the AccountState property of the BankAccount class to a different state if all the classes inheriting from AccountStates are singletons? If yes and you have used the same pattern as you described above then:

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

Also, if you are interested in finding out more about thread safe instantiation of singleton, have a look at MSDN

Upvotes: 1

Related Questions