Friday, June 23, 2017

Null Object pattern

·         The null object pattern falls under Behavior design pattern
·         The object is null but your code can still run.
·         The use of Null Object pattern simplifies the client code and makes it less error prone.
·         The use of the Null Object pattern is that it doesn't require a null check to prevent a crash or error.
·         Consider an application which does orders based on the discount.
Below is the Order class:
[Code]
Let us say we have two types of discount “Premium discount “and “Festival discount”
[Code]
Now we can able to create Premium and Festival orders using Premium and Festival discount
Now let’s take an example where we need to create an order for customer who had no discount.
[Code]
Now the applications crashes
[Image]
We need to create a discount class which does NO discount calculation as shown in the below code.
[Code]

Now the below client call to order object would not crash.
[Code]

Reference : https://www.codeproject.com/Articles/1042674/NULL-Object-Design-Pattern

Wednesday, May 31, 2017

Template Pattern


As the name Template suggests, is a kind of layout available for some kind of process that we can modify as needed and use it. We have some sub-tasks to complete a big task that we can use as per our situation requirements. So technically speaking, we make the sub-tasks as abstract and implement them, as per our needs, in different cases. But one thing remains common; the overall steps of the entire procedure or the algorithm, in other words first Step 1, then Step 2, then Step 3 and so on, that remain the same in their execution order

What is Template Method Pattern:

“According to the GoF's definition: Defines the skeleton of an algorithm in an operation, deferring some steps to sub-classes. The Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm's structure”

Example:

Let us have a class for Data Exporter and below are the steps performed (this is same for all type of data converter i.e. the algorithm structure remains same)
Step 1: Read Data
Step 2: Format Data
Step 3: Export Data
[Code]

The implementation of the ReadData and FormatData will not change as per the requirements. The only changeable part is the ExportData function whose implementation will change based on the target file to export to.

abstract class DataExporter
{
    // This will not vary as the data is read from sql only
    public void ReadData()
    {
        Console.WriteLine("Reading the data from SqlServer");
    }

    // This will not vary as the format of report is fixed.
    public void FormatData()
    {
        Console.WriteLine("Formating the data as per requriements.");
    }

    // This may vary based on target file type choosen
    public abstract void ExportData();        

    // This is the template method that the client will use.
    public void ExportFormatedData()
    {
        this.ReadData();
        this.FormatData();
        this.ExportData();
    }
}

So if we need to export the data to an excel file we need a ConcreteClass for that, we will create a concrete class ExcelExporter

class ExcelExporter : DataExporter
{
    public override void ExportData()
    {
        Console.WriteLine("Exporting the data to an Excel file.");
    }
}

Also another concrete class PDFExporter

class PDFExporter : DataExporter
{
    public override void ExportData()
    {
        Console.WriteLine("Exporting the data to a PDF file.");
    }
}

DataExporter class will be used by the application and the required implementation of the algorithm will be taken from the derived classes.

static void Main(string[] args)
{
    DataExporter exporter = null;

    // Lets export the data to Excel file
    exporter = new ExcelExporter();
    exporter.ExportFormatedData();

    Console.WriteLine();

    // Lets export the data to PDF file
    exporter = new PDFExporter();
    exporter.ExportFormatedData();
}

So we have seen that the actual algorithm to export the data remains the same but the part where the file type to export to can be moved into the derived classes. The template method will remain oblivious to the implementation and will run the algorithm. At run time it will call the derived classes overridden function to execute the required functionality.

Another example is web page creation, all web pages have a something common Header and Footer but their content is different, and the algorithm is same creating the webpage (i.e. step 1: create header, step:2 create page content, step 3: create footer)




Chain of Responsibility pattern

According to the GOF’s definition:
“Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it”

This is how Chain of responsibility works:
1. The base class maintains a “next” pointer.
2. Each derived class implements its contribution for handling the request
3.  If the request is not able to be processed by the class then it delegates to the “next” pointer of the base class and so it goes on.
4. The client forms the order/links the chain.
Chain of Responsibility simplifies object interconnections. Instead of senders and receivers maintaining references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain.
Do not use Chain of Responsibility when each request is only handled by one handler, or, when the client object knows which service object should handle the request.

Example:
Consider a leave management system, If you applying for not more than 5 leaves then directly your reporting manager can approve it, if it is more than 5 then he will decline it and you have to again move the request to Program manager, instead you moving the request, the reporting manager can directly delegate to Program manager and Program manager to Management and so on.
Handler: An interface or abstract class which contains the “next” handler.
[Code]
Concrete handler: Actual request handlers
[Code]
Client: The employee who request for leave
[Code]

UML:

Examples:
1. ATM machine
2.  Leave management system
  

 References:
1. https://sourcemaking.com/design_patterns/chain_of_responsibility
2. http://www.dotnettricks.com/learn/designpatterns/chain-of-responsibility-design-pattern-dotnet

3. https://dotnetfreakblog.wordpress.com/2013/09/16/chain-of-responsibility-design-pattern/

Command Pattern

1. http://alvinalexander.com/java/java-command-design-pattern-in-java-examples
2. https://www.javacodegeeks.com/2012/11/by-your-command-command-design-pattern.html
3. https://code.msdn.microsoft.com/windowsapps/Design-Patterns-Command-1962d567
4. http://www.c-sharpcorner.com/UploadFile/80ae1e/command-design-pattern/
5. https://stackoverflow.com/questions/6293171/i-dont-understand-why-a-command-pattern-is-convenient-in-object-oriented-design

Strategy Pattern

Strategy (from Greek: strategia, "art of troop leader; office of general, command, generalship") is a high level plan to achieve one or more goals under conditions of uncertainty.  A strategy describes how the ends (goals) will be achieved by the means (resources)

There are many scenarios in application development where there are multiple ways of doing the same operation. We want our application to have the possibility of using all these ways of performing the operations.

Below are some of the examples:

·      Online payment using a portal, I could choose to pay using net banking, or use a debit card, or use a credit card, or use PayPal for making the payment. All these are ways of performing the same operations. Though every choice will have to follow a different application logic, i.e. separate code.

·       Sorting algorithm: where the intention is same (i.e. need to sort, but by different ways).

·    Travel mode: one wants to arrive to different place but using different mode based on the current situation (he has less money – use cycle; has less time - use flight; it’s raining - use car), so he makes a clear strategy before his travel , he hires cycle, borrows money from his friend for the flight, books car tentatively).

So we have a situation to develop the application in such a way that for any operation the user could choose one of many available options, then perhaps that is the right place to incorporate the Strategy pattern.

The philosophy of the Strategy pattern is to have multiple strategies for doing some operation and let the user choose (or some algorithm based on input data) the appropriate strategy to carry out the operation.

GoF defines the Strategy pattern as “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 

·    Strategy: This is the interface common to all algorithms. Context uses this interface to perform the operations.
·     ConcreteStrategy: This is the class that implements the actual algorithm.
·   Context: This is the client application that performs the decision making for which strategy should be used and uses the Strategy interface (which is referring to a ConcreteStrategy object) to perform the operations.


To understand these concepts, let us take an application for converting audio files from Wav to MP3. Here the user will have an option of selecting the source .wav file and then select the quality of the target MP3 file to be created. The user interface will provide the user with three quality values for the target file.

In our code what we will do is that we will create multiple strategies each that we will be using are to define the quality of the output. We are implementing all these separate strategies so that conversion code will remain unaffected by the code that is specific to dealing with the quality of the output. The actual code that is doing the conversion will be independent of the implementation details of these different strategies and will work in the same fashion for any selected strategy or even when the new strategies are added.


IWavToMp3ConvertionStrategy interface for conversion:
interface IWavToMp3ConvertionStrategy
{
 void Convert();
}

Strategy class for low quality conversion
class LowQualityConversionStrategy : IWavToMp3ConvertionStrategy
{
 public void Convert()
 {
  Console.WriteLine("Low quality conversion performed");
 }
}

Strategy class for average quality conversion:
class AverageQualityConversionStrategy : IWavToMp3ConvertionStrategy
{
 public void Convert()
 {
  Console.WriteLine("Average quality conversion performed");
 }
}

Strategy class for high quality conversion:
//Strategy class for average quality conversion
class HighQualityConversionStrategy : IWavToMp3ConvertionStrategy
{
 public void Convert()
 {
  Console.WriteLine("High quality conversion performed");
 }
}
WavToMP3Convertor class to convert to different type:
public class WavToMP3Convertor
{
 AudioFile m_fileData = null;
 IWavToMp3ConvertionStrategy m_Convertor = null;

 public WavToMP3Convertor(AudioFile fileData)
 {
  m_fileData = fileData;            
 }
 
public void Convert(IWavToMp3ConvertionStrategy convertor)
 {
  m_Convertor = convertor;
  m_Convertor.Convert();            
 }
}
In main program we get use input and do the conversion:
static void Main(string[] args)
{
 IWavToMp3ConvertionStrategy selectedStrategy = null;

 Console.WriteLine("Assuming the file for conversion has been selected already");
 AudioFile file = new AudioFile { Title = "Sample File" };

 // Let us try to emulate the selection of quality here
 Console.WriteLine("Enter the type of output");
    
 int choice = Console.Read();

 // Based on the user's choice will select strategy to convert the file
 if (choice == '1')
 {
  selectedStrategy = new LowQualityConversionStrategy();                
 }
 else if (choice == '2')
 {
  selectedStrategy = new AverageQualityConversionStrategy();                
 }
 else if (choice == '3')
 {
  selectedStrategy = new HighQualityConversionStrategy();                
 }

 // Now the code which is doing the conversion. this code will
 // not be changes even if we implement more strategies
 if (selectedStrategy != null)
 {
  WavToMP3Convertor convertor = new WavToMP3Convertor(file);
  convertor.Convert(selectedStrategy);
 }
}
References:
https://sourcemaking.com/design_patterns/strategy
http://www.dofactory.com/javascript/strategy-design-pattern
https://stackoverflow.com/questions/5375187/strategy-design-pattern-and-factory-method-design-pattern

Friday, May 19, 2017

Structural Design Pattern

  • Structural design patterns are concerned with how classes and objects can be composed, to form larger structures.
  • The structural design patterns “simplifies the structure by identifying the relationships”.
  • These patterns focus on, how the classes inherit from each other and how they are composed from other classes.
  • There are 7 types of structural pattern:
1.       Adapter Pattern
2.       Bridge Pattern
3.       Composite Pattern
4.       Decorator Pattern
5.       Facade Pattern
6.       Flyweight Pattern
7.       Proxy Pattern

Behavioral Design Patterns

  • Behavioral design patterns are the ones which are concerned with the interaction and responsibility of objects.
  • In these design patterns, the interaction between the objects should be in such a way that they can easily talk to each other and still should be loosely coupled.
  • That means the implementation and the client should be loosely coupled in order to avoid hard coding and dependencies.
  • There are 12 types of  Behavioral design patterns:
2.       Command Pattern
3.       InterpreterPattern
4.       IteratorPattern
5.       Mediator Pattern
6.       Memento Pattern
7.       Observer Pattern
8.       State Pattern
9.       StrategyPattern
10.    TemplatePattern
11.    Visitor Pattern
12.    Null Object


Memento design pattern

Problem statement :

       Consider creating an gaming  application, which contains level 1 to 5.
       The player will score different scores  and points at each level.
       When the player reaches Level 1 the application will update the Score and Level (ex: Level =1 ; Score = 100 and other points).
       When the player reaches Level 2 the application  will update the Score and Level (ex: Level =2 ; Score = 200 and other points).
       When the player reaches Level 3 the application  will update the Score and Level (ex: Level =3 ; Score = 300 and other points).
       When the player reaches Level 4  he scores 350 but he has lost a game life .
       Now the application  should restrict moving  further level and should restore back to Level 3 with the Score = 300 and points, but it cannot as the application doesn't know the previous level  Score and points as they are already updated.
       To overcome the above issue, we can use the Memento pattern.


What is Memento :


      •   Memento – Reminder, token, trophy. “Object to you keep to remember a person, place ,event”.
       Memento pattern falls under behavioral pattern category. –    Behavioral design patterns are concerned with the interaction and  responsibility of objects.
       The memento pattern is a software design  pattern that provides the ability to restore an object to its previous state (undo via rollback)
       Memento means a reminder of past events . In Memento pattern, we do not create a copy of an object. We create Mementos that hold the state of an object and it might include full object or elements of an object that needs to be stored.
       Memento protects encapsulation and avoids exposing originator's internal state and implementation.

Implementation : 

       Originator : Class to hold the main data (level , score and points), i.e the data of the player
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace MementoPattern  
 {  
   /// <summary>  
   /// Orignator class  
   /// </summary>  
   public class PlayerStatistics  
   {  
     public int LevelID { get; set; }  
     public int Score { get; set; }  
     public DateTime Time { get; set; }  
     public int Name { get; set; }  
     public int Points { get; set; }  
     public string GraphicType { get; set; }  
     /// <summary>  
     /// Save the player statics to a memento  
     /// </summary>  
     /// <param name="playerStatistics"></param>  
     /// <returns></returns>  
     public PlayerStatisticsMemento CreateMemento(PlayerStatistics playerStatistics)  
     {  
       return new PlayerStatisticsMemento(playerStatistics.LevelID, playerStatistics.Score, playerStatistics.Time, playerStatistics.Points);  
     }  
     /// <summary>  
     /// Restore the player statistics to a previous state held by memento  
     /// </summary>  
     /// <param name="checkPointMemento"></param>  
     public void SetMemento(PlayerStatisticsMemento checkPointMemento)  
     {  
       this.LevelID = checkPointMemento._LevelID;  
       this.Score = checkPointMemento._Score;  
       this.Time = checkPointMemento._Time;  
     }  
     public void PrintStatistics()  
     {  
       Console.WriteLine("CheckPoint Time:" + this.Time);  
       Console.WriteLine("Level is:" + this.LevelID);  
       Console.WriteLine("Score is:" + this.Score);  
     }  
   }  
 }  
       Memento   : Class used to store  the snapshot of the origin data  (Originator class) only with the properties which are needed to be captured.
1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.Linq;  
4:  using System.Text;  
5:  using System.Threading.Tasks;  
6:  namespace MementoPattern  
7:  {  
8:    /// <summary>  
9:    /// Memento  
10:    /// </summary>  
11:    public class PlayerStatisticsMemento  
12:    {  
13:      public int _LevelID { get; set; }  
14:      public int _Score { get; set; }  
15:      public DateTime _Time { get; set; }  
16:      public int _Points { get; set; }  
17:      public PlayerStatisticsMemento(int level, int score, DateTime time, int points)  
18:      {  
19:        this._LevelID = level;  
20:        this._Score = score;  
21:        this._Time = time;  
22:        this._Points = points;  
23:      }  
24:    }  
25:  }  

      CareTaker : To hold  all the memento objects , i.e which holds the snapshot of the original data.
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace MementoPattern  
 {  
   /// <summary>  
   /// Caretaker to hold the undo/redo.  
   /// </summary>  
   public class CareTaker  
   {  
     private static CareTaker _instance;  
     private PlayerStatisticsMemento _playerStaticsMemento;  
     private CareTaker()  
     {  
     }  
     public static CareTaker Instance  
     {  
       get  
       {  
         if (_instance == null)  
         {  
           _instance = new CareTaker();  
         }  
         return _instance;  
       }  
     }  
     public PlayerStatisticsMemento PlayerStaticsMemento  
     {  
       get  
       {  
         return _playerStaticsMemento;  
       }  
       set  
       {  
         _playerStaticsMemento = value;  
       }  
     }  
   }  
 }  

Main program:


1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.Linq;  
4:  using System.Text;  
5:  using System.Threading.Tasks;  
6:  namespace MementoPattern  
7:  {  
8:    class Program  
9:    {  
10:      static void Main(string[] args)  
11:      {  
12:        PlayerStatistics _statistics = new PlayerStatistics();  
13:        _statistics.LevelID = 1;  
14:        _statistics.Score = 100;  
15:        _statistics.Time = DateTime.Now;  
16:        _statistics.PrintStatistics();        
17:        _statistics.LevelID = 2;  
18:        _statistics.Score = 200;  
19:        _statistics.Time = DateTime.Now;  
20:        _statistics.PrintStatistics();  
21:        _statistics.LevelID = 3;  
22:        _statistics.Score = 300;  
23:        _statistics.Time = DateTime.Now;  
24:        _statistics.PrintStatistics();  
25:        CareTaker.Instance.PlayerStaticsMemento = _statistics.CreateMemento(_statistics);        
26:        _statistics.LevelID = 4;  
27:        _statistics.Score = 350;  
28:        _statistics.Time = DateTime.Now;  
29:        _statistics.PrintStatistics();  
30:        Console.WriteLine("\nPlayer lost his life here so retore to level 3\n");        
31:        _statistics.SetMemento(CareTaker.Instance.PlayerStaticsMemento);  
32:        _statistics.PrintStatistics();  
33:        Console.ReadLine();  
34:      }  
35:    }  
36:  }  

UML Diagram :



Benefit & Examples:

1. Improve Performance:
      • Sine value calculation.

2. Undo/Roll back Operations:
      • Ctrl-Z in MS Word
      • Bank Transaction
      • Cancel operation in Forms

Iterator Design Pattern

Definition:
       Iterator pattern falls under behavioural pattern category.
       In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
       This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation.
       What Iterator patterns is NOT? -  repeat task / solving solution

Purpose:
       Easy access to elements of container.
       Avoid data tampering at client side
       Perform simultaneous Iterators

Why Iterator Pattern (Problem statement):
       Consider an application used to print the details of a bank (its name and its manager name). For now only 3 banks details are known, and this is how it prints.

        Display(bank1.BankName);
     Display(bank1.Locatioin);
     Display(bank2.BankName);
     Display(bank2.Location);

       Let’s say now 100 bank details are known, now the complexity arises, as the application will now need to print all the 100 bank details one by one.
       To overcome the above issue, we can use the Iterator pattern.

Implementation:

       Step 1: Store all the objects ( all bank details ) in a container (list).
                private ArrayList m_ArrBank = new ArrayList();
                 m_ArrBank .Add(new Bank("ABC", “Location1"));
                 m_ArrBank .Add(new Bank("XYZ", " Location2"));
                 m_ArrBank .Add(new Bank("TUV", "Location3”));

       Step2: Access all the elements of the list by using an Iterator ( i.e. by using foreach)
                 foreach (Bank item in m_ArrBank )  // Iterator
                 {
                      Display(item.Location);
                      Display(item.BankName);
                 }

UML :



Example in C# :


Examples of Iterator :

  C++
        Template Library Containers implement their iterators
        Template Library algorithm are defines in terms iterator
  C#
        IEnumerable and IEnumurator are used
  Java
        SDK defines iterator interface
        Collections implement their iterators
  SQL
        Cursor is an iterator.
  TV Remote control

Types of Iterator :

       Internal Iterator
       External Iterator
       Single Integral Iterator
       Multiple Integral Iterator

Thursday, May 18, 2017

Tread vs ThreadPool

The main difference is whether you manage the thread lifetime yourself (Thread), or you take advantage of the "pool" of threads the framework already creates.

Using ThreadPool.QueueUserWorkItem will (often) use a thread that already exists in the system. This means you don't have the overhead of spinning up a new thread - instead, a set of threads is already there, and your work is just run on one of them. This can be especially beneficial if you're doing many operations which are short lived.

When you use new Thread, you actually spin up a new thread that will live until your delegate completes its execution.

Note that, as of .NET 4 and 4.5, I'd recommend using the Task and Task<T> types instead of making your own threads, or using ThreadPool.QueueUserWorkItem. These (by default) use the thread pool to execute, but provide many other useful abstractions, especially with C# 5 and the await/async keywords
.
The BackgroundWorker class is an abstraction over the thread pool. It uses the ThreadPool to queue up "work" (your DoWork event handler), but also provides extra functionality which allows progress and completion events to be posted back to the initial SynchronizationContext (which, in a GUI program, will typically be the user interface thread). This simplifies tasks where you want to update a UI for progress or completion notifications as background "work" is running on a background thread.