Nawzir Kadiwal Nawzir Kadiwal - 1 month ago 6
ASP.NET (C#) Question

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.

Answer

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