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