Showing posts with label design pattern in c#. Show all posts
Showing posts with label design pattern in c#. Show all posts

Monday, 31 May 2021

Command Design Pattern in C#

    

 Introduction

    Command design pattern encapsulates request as an object which has all the information needed to perform an action or invoke a method or trigger an event at later time. It supports undoable action.

It is a behavior design pattern.

It  deals with below problems

1. Decouples the request receiver and request invoker.

2. Code is extensible as new Receiver and command be added in future.

UML Diagram


Example Basic structure program

using System;

public class Program
{
public static void Main()
{
var receiver = new Receiver();
var command = new ConcreteCommand(receiver);
var invoker = new Invoker(command);
invoker.DoAction();
}
}

public class Receiver
{
public void DoOperation()
{
    Console.WriteLine("Receiver is doing the operation");
}
}

public interface ICommand
{
    void Execute();
}

public class ConcreteCommand:ICommand
{
        private Receiver _receiver;
        public ConcreteCommand(Receiver receiver)
        {
            _receiver = receiver;
        }

public void Execute()
{
    _receiver.DoOperation();
}
}

public class Invoker
{
    private ICommand _command;
    public Invoker(ICommand command)
    {
        _command = command;
    }

    public void DoAction()
    {
        _command.Execute();
    }
}

In the above code, we can see Command and Invoker have been created separately. This means 
Invoker can execute the command at a later point of time or deferred execution of command.
Command can be queued and executed.
Command can be created on one server & can be executed on another server in distributed systems.
Waiter and Chef (cook) are very good example of command pattern. As Waiter takes the order from the customer, he passed it to chef. Chef prepares the food and waiter serves it to customer.  

Real World Example
    Write to me for real world example.










Wednesday, 26 May 2021

Observer Design Pattern in C#

 Introduction

    In Observer design pattern an object 'subject' maintains the list of its dependent objects , observers, and notify them whenever there is a change in its state. It is a behavior design pattern.

It deals with below problems

- Define One to many dependency between objects without making them tightly coupled.

- Whenever there is a change in one object, other objects should get notified or updated.

UML diagram



Basic code example


public class Subject

    private IList<IObserver> _observers;
    private int state;

    // On change of this property, observers will be notified
    public int State{
        get{return state;}
        set{state = value; this.Notify();}
    }

    public Subject()
    {
        _observers = new List<IObserver>();
    }

    // Register Observer to get notification
    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    //Remove Observer to stop getting notification
    public void RemoveObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    //Send notification
    private void Notify()
{
var eventArg = new EventArg(){Value=4};
foreach(var observer in _observers)
observer.Execute(eventArg);
}
}

//Observer interface
public interface IObserver
{
    void Execute(EventArg eventarg);
}

public sealed class EventArg
{
public int Value{get;set;}
}

//Concrete ObserverA implementation of IObserver
public class ObserverA:IObserver
{
    public void Execute(EventArg eventArg)
{
Console.WriteLine($"ObserverA is execute & eventArg : {eventArg.Value}");
}
}

//Concrete ObserverB implementation of IObserver
public class ObserverB:IObserver
{
    public void Execute(EventArg eventArg)
{
Console.WriteLine($"ObserverB is execute & eventArg: {eventArg.Value}");
}
}

Program 
using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
var subject = new Subject();
subject.RegisterObserver(new ObserverA());
subject.RegisterObserver(new ObserverB());
subject.State = 4;
}
}

//Since subject State property is changed when it is assigned with value 4, Observers get notification
//Output
    ObserverA is execute & eventArg : 4
   ObserverB is execute & eventArg: 4

In DotNet for this purpose there is Delegate & Event Type to achieve the same.

Tuesday, 18 May 2021

Strategy Design Pattern in C#

Introduction

    Strategy design pattern enables to select one of the algorithms at run time. It is a behavior design       pattern and is based on Inheritance principle.
    
It deals with
    1. Multiple possible algorithms for a problem. Or When there is a family of algorithm for a problem. 
    2. Dynamically any algorithm can be selected based on certain input.




   Example

  1. In eCommerce application online payment system, there are multiple payment options
    • Cash on delivery
    • CreditCard
    • UPI 
    • Internet Banking etc.
    2. String Sorting 
    • Bubble Sort
    • Merge Sort
    • Quick Sort etc.
   3. A manufacturing company pays its employee on weekly basis. If amount is less than 2000 dollor, it it is paid in cash and employee sign on voucher against cash received. If amount is more than or equal to 2000 dollor it is paid by cheque.  
    In this scenario, payment can be implmented as Cash and Cheque. Amount is the factor which drive which payment option will be selected.

This design pattern is one of the most frequently used one.

Implementation


  public interface IStrategy
 {
  void Execute();
 }

public class StrategyA: IStrategy
{
public void Execute()
{
Console.WriteLine("This is implementation of StrategyA::Execute");
}
}

public class StrategyB: IStrategy
{
public void Execute()
{
Console.WriteLine("This is implementation of StrategyB::Execute");
}
}

 public class Context
{
    private IStrategy _strategyA, _strategyB;

    public Context()
   {
     _strategyA = new StrategyA();

                _strategyB= new StrategyB(); 

    }

    public void OperationA()
    {
        Console.WriteLine("Context OperationA method");
        _strategyA.Execute();
       _strategyB.Execute();

    }
}



Note: Most of the time Strategy is used along with factory. For real world example please write to me.

 
        

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