State Pattern Code Review

Define the Pattern Interface and Handler Objects

Code Download

  • Download Description:state pattern download
  • .NETFramework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:9 KB

Code Review

Code Walkthrough

Define the IState interface to be used as the "blueprint" for the main State classes.

interface IState { void Deposit(Context context, Double amount); Boolean Withdraw(Context context, Double amount); Boolean PayInterest(Context context); }

The RedState class (object) represents one particular state.

class RedState : IState { public void Deposit(Context context, double amount) { context.Balance += amount;
if (context.Balance > 0) { context.State = new SliverState(); } } public Boolean Withdraw(Context context, double amount) { context.Balance -= 15.00; Console.WriteLine("No funds available for withdrawal!\n"); return (false); } public Boolean PayInterest(Context context) { Console.WriteLine("No interest paid!\n"); return (false); } }

The SliverState class (object) represents another available state, and is able to update the State object as required.

class SliverState : IState { public void Deposit(Context context, double amount) { context.Balance += amount; UpdateState(context); } public Boolean Withdraw(Context context, double amount) { context.Balance -= amount; UpdateState(context); return (true); } public Boolean PayInterest(Context context) { Console.WriteLine("No interest paid!\n"); return (false); } private void UpdateState(Context context) { if (context.Balance < 0) { context.State = new RedState(); } else if (context.Balance > 1000) { context.State = new GoldState(); } } }

The GoldState class (object) represents another available state, and is able to update the State object as required.

class GoldState : IState { public void Deposit(Context context, double amount) { context.Balance += amount; UpdateState(context); } public Boolean Withdraw(Context context, double amount) { context.Balance -= amount; UpdateState(context); return (true); } public Boolean PayInterest(Context context) { context.Balance *= 1.05; UpdateState(context); return (true); } private void UpdateState(Context context) { if (context.Balance < 0) { context.State = new RedState(); } else if (context.Balance < 1000) { context.State = new SliverState(); } } }