State Pattern Code Review
Define the Context Object
Code Review
- State Pattern Code Review: Define the Pattern Interface and Handler Objects
- State Pattern Code Review: Define the Context Object
- State Pattern Code Review: Use the State Pattern
Code Walkthrough
The Context class (object) initialises the State object and invokes methods on the State class (object).
class Context
{
public IState State { get; set; }
public Double Balance { get; set; }
private String m_owner;
public Context(String Owner) { this.m_owner = Owner; this.State = new SliverState(); }
public void Deposit(Double amount) { State.Deposit(this, amount); Console.WriteLine(String.Format("Deposited {0:C}", amount)); this.ShowBalance(); } public void Withdraw(Double amount) { if (State.Withdraw(this, amount)) { Console.WriteLine(String.Format("Withdrew {0:C}", amount)); } else { Console.WriteLine("\t15% charge applied"); } this.ShowBalance(); } public void PayInterest() { if (State.PayInterest(this)) { Console.WriteLine("Interested Paid"); this.ShowBalance(); } } private void ShowBalance() { Console.WriteLine(String.Format("\tBalance {0:C}", this.Balance)); Console.WriteLine(String.Format("\tStatus {0}\n", this.State.GetType().Name)); } }
private String m_owner;
public Context(String Owner) { this.m_owner = Owner; this.State = new SliverState(); }
public void Deposit(Double amount) { State.Deposit(this, amount); Console.WriteLine(String.Format("Deposited {0:C}", amount)); this.ShowBalance(); } public void Withdraw(Double amount) { if (State.Withdraw(this, amount)) { Console.WriteLine(String.Format("Withdrew {0:C}", amount)); } else { Console.WriteLine("\t15% charge applied"); } this.ShowBalance(); } public void PayInterest() { if (State.PayInterest(this)) { Console.WriteLine("Interested Paid"); this.ShowBalance(); } } private void ShowBalance() { Console.WriteLine(String.Format("\tBalance {0:C}", this.Balance)); Console.WriteLine(String.Format("\tStatus {0}\n", this.State.GetType().Name)); } }
Printer Friendly Version
Add to Favourites
DotNet Kicks
Digg
del.icio.us
Live Favourites
ma.gnolia
reddit
Slashdot
Technorati
Yahoo!