Friday 14 May 2021

State Design Pattern in C#

Introduction 

State Design Pattern is a behavior design pattern. It allows an object to change or alter its behavior on change of its internal state.

It deals with 2 main problems

a. The object should change its behavior when its internal state change.

b. State specific behavior should be defined (programmed) independently. This means on adding new behavior will not impact on existing behaviors.

UML Class Diagram



Examples:

            Below are some examples

1. In Banking System, based on Average Monthly balanced in a saving account, bank makes the saving account as Normal, Classic, Privilege category.

  When account is Normal,

  • user will be charged for Debit card
  • minimum balance is 5000/- monthly
  • 5 times free withdraw money from another bank ATM
  • Daily max withdraw limit is 10000
  • If 5balance is more than 15000 and less than 25000, account will be promoted to Classic.
  • If balance is more than 25000, account will be promoted to Privilege.

 When account is Classic

  • user will not be charged for Debit card
  • minimum balance is 15000/- monthly
  • 10 times free withdraw money from another bank ATM
  • daily max withdraw is 20000.
  • If balance is more than 25000, account will be promoted to Privilege.
  • If balance is less than 25000, account will become Normal.

When account is Privileged 

  • user will not be charged for Debit card
  • minimum balance is 25000/-
  • unlimited free withdraw from another bank ATM
  • daily max withdraw is 50000/-
  • free Cheque book
  • personalized banker for help
  • personal loan on 1% less interest rate
  • If balance is less than 25000 and more than 15000 account will become classic
  • If balance is less than 15000, account will become Normal.

2. Public transport e.g. Bus

When Bus is static at bus stop, 

  • Doors should be opened
  • Passengers can get on of the bus.
  • Passengers can get down of the bus.

When Bus is moving,

  • Doors should be closed
  • Passengers can’t get on or get down of the bus.      

3. Vending Machine

  • Ready State: It can accept payment for cash / online accepting
  • Item-Selection State: Customer can select an item
  • Balance-Dispense: Dispense the balance amount
  • Machine is in Item-Dispense State: Selected Item will be dispensed
  • Machine is in Cancel Item State: User cancelled the item; money will be returned.
  • Inventory-Replenishment State: Items are replenished in the vending machine      

Implementation:

 Context Class

Context class has reference of State.

By default when Context Class is created, it is in StateA.



State 


StateA and StateB


Based on ChangeState property, context is changing from StateA to StateB.

Sample program is 

State Design Pattern in C#


Real world example

subscribe to get real world example

 

 


No comments:

Post a Comment