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.

FlagsAttributes in C#

 Introduction

    In C# enum is a named integer constant. But a type can have only one enum value. FlagsAttribute is used to assign multiple enum values.

Example

using System;

public class Program

{

public static void Main()

{

var rocky = new Person("Rock", Vehicle.BMWX5);

var peter = new Person("Peter Parker", Vehicle.Highlander);

rocky.PersonInfo();

            //Output: Rock owns BMWX5

peter.PersonInfo();

            //Output: Peter Parker owns Highlander

}

}

public class Person

{

public string Name{get;set;}

public Vehicle Vehicle{get;set;}

public Person(string name, Vehicle vehicle)

{

Name = name;

Vehicle=vehicle;

}

public void PersonInfo()

{

Console.WriteLine($"{Name} owns {Vehicle}");

}

}

public enum Vehicle

{

none=0,

BMWX5=1,

LandRover=2,

LincolnAviator=4,

Highlander=8

}

In the above program, one person can own one vehicle.

What if a person owns 2 or more vehicles. In this case FlagsAttribute is useful.

using System;

public class Program

{

public static void Main()

{

                //vehicle2 is now represents 2 vehicles BMWX5 and Highlander both.

var vehicle2 = Vehicle.BMWX5|Vehicle.Highlander;

     var rocky = new Person("Rock", Vehicle.BMWX5);

var peter = new Person("Peter Parker", Vehicle.Highlander);

                // John owns vehicle2 means he has 2 vehicles.

var john = new Person("John", vehicle2);

rocky.PersonInfo();

peter.PersonInfo();

john.PersonInfo();

                //Output: John owns BMWX5, Highlander

}

}


public class Person

{

public string Name{get;set;}

public Vehicle Vehicle{get;set;}

public Person(string name, Vehicle vehicle)

{

Name = name;

Vehicle=vehicle;

}

public void PersonInfo()

{

Console.WriteLine($"{Name} owns {Vehicle}");

}

}

[Flags]

public enum Vehicle

{

none=0,

BMWX5=1,

LandRover=2,

LincolnAviator=4,

Highlander=8

}  

Complete Code


Tuesday 25 May 2021

Rest Principles

 Introduction

    Representational State Transfer (REST) is an architectural style that abstracts the architectural elements within a distributed hypermedia system. It was first presented by  Roy Fielding in 2000.

The REST architectural style describes six constraints applied to the architecture which are described below:


Client–Server

This princples is based on separation of concerns principles. It is about separating client interface from data storage concers. This means client (facing) application should not handle data storage or management activity while server should not handle user interface or user state or how user is interacting with the application.

Since both the client and server are independent of each other. They can be developed independently and will be more manageable and scalable.

Stateless

Server should not store any client context information. Each client request shuould contain all the necessary information to handle the request. Session state should be held in the client

Cacheable

Client can cache responses. Response can be, implicitly or explicitly, labeled as cacheable or non-cacheable. So that client can reuse the same response data in future for equivalent request.

Layered system

It allows to use multiple hierarchical layers to compose the application. e.g. API can be deployed to Server X, database on Server B etc.

A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way.

Intermediary servers may be useful in load-balancing, cache management, security etc.

Code on demand (optional)

Servers can temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript. "Code on demand" is the only optional constraint of the REST architecture.

 Uniform interface

The uniform interface between clients and servers, simplifies and decouples the architecture, which enables each part to evolve independently. The four guiding principles of this interface are detailed below.

    1. Identification of resources
    2. Resource manipulation through representations
    3. Self-descriptive messages
    4. Hypermedia as the engine of application state 


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