Introduction:
Sometimes you want to build a class where its behavior changed according to its state. State Design pattern provides a good class structure to solve this issue. State Design pattern also known as Object for state pattern is used to represent the state of an object and the object behavior will changed according to state changes.
Example:
static void Main(string[] args) { WaterCompound c = new WaterCompound(0); c.IncreaseTempreture(10); c.IncreaseTempreture(100); c.DecreaseTempreture(99); c.DecreaseTempreture(40); c.DecreaseTempreture(50); Console.ReadKey(); } class WaterCompound : Compound { public WaterCompound(int temp) { _state = new LiquiedState(this,temp,0,100); } } public class Compound { public State _state; public void IncreaseTempreture(int temp) { _state.IncreaseTempreture(temp); Console.WriteLine(” Balance = {0:D}”, _state.Tempreture); Console.WriteLine(” Status = {0}\n”, this._state.GetType().Name); Console.WriteLine(“—————-“); } public void DecreaseTempreture(int temp) { _state.DecreasseTempreture(temp); Console.WriteLine(” Balance = {0:D}”, _state.Tempreture); Console.WriteLine(” Status = {0}\n”, this._state.GetType().Name); Console.WriteLine(“—————-“); } } public abstract class State { protected Compound _compound; public int LowerTempLimit { get; set; } public int UpperTempLimit { get; set; } public int Tempreture { get; set; } public abstract void IncreaseTempreture(int temp); public abstract void DecreasseTempreture(int temp); } class BoilingState:State { public BoilingState(Compound c,int temp,int lowerTemp,int Uppertemp) { Tempreture = temp; base._compound = c; LowerTempLimit = lowerTemp; UpperTempLimit = Uppertemp; } public override void IncreaseTempreture(int temp) { Tempreture += temp; } public override void DecreasseTempreture(int temp) { Tempreture -= temp; if (Tempreture < LowerTempLimit) base._compound._state = new LiquiedState(_compound, Tempreture,0,100); } } class FreezingState:State { public FreezingState(Compound c,int temp,int lowerTemp,int Uppertemp) { Tempreture = temp; base._compound = c; LowerTempLimit = lowerTemp; UpperTempLimit = Uppertemp; } public override void IncreaseTempreture(int temp) { Tempreture += temp; if (Tempreture > UpperTempLimit) _compound._state = new LiquiedState(_compound, Tempreture,0,100); } public override void DecreasseTempreture(int temp) { Tempreture -= temp; } } class LiquiedState:State { public LiquiedState(Compound c,int temp,int lowerTemp,int Uppertemp) { Tempreture = temp; base._compound = c; LowerTempLimit = lowerTemp; UpperTempLimit = Uppertemp; } public override void IncreaseTempreture(int temp) { Tempreture += temp; if (Tempreture > UpperTempLimit) _compound._state = new BoilingState(_compound, Tempreture,101,100000); } public override void DecreasseTempreture(int temp) { Tempreture -= temp; if (Tempreture < LowerTempLimit) _compound._stae = new FreezingState(_compound, Tempreture,-150,-1); } } |