Strategy Design Pattern

Please check out my latest video on the Strategy Design Pattern.

This video link posted above describes two very simple and practical examples of the Strategy Design Pattern. The first example explains strategy in terms of a floor cleaning Robot. A tool that is best suited for a floor type can be attached to the floor cleaning robot and that each such tool represents a concrete strategy. Each tool has to fit a generic slot in the Robot and that represents an abstract strategy. The Robot itself represents a context. Class diagram of this scenario is
:

In another example, a simple application is shown that implements two approaches to read an XML file. The first approach loads the entire XML file into memory and uses XPath searches to find a node matching a criteria. The second approach uses line-by-line file reading approach. The class diagram of this implementation is

Source Code of the XML File Search Application:

Abstract Strategy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace StrategyPatternConsoleApplication
{
//this is the abstract strategy
public interface ISearchXmlFileStrategy
{
// All concrete strategies must implement this method
string GetCustomerNameByCustomerID(String customerId, String filePath);
}
}

Concrete Strategy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace StrategyPatternConsoleApplication
{
//concrete strategy loads xml document into memory
//then does in memoryreading
public class MemorySearchXmlFileStrategy : ISearchXmlFileStrategy
{
///
 
/// Invokes strategy interface method
///
 
///Customer identifier
///Xml file name with path
/// Customer name
public string GetCustomerNameByCustomerID(String customerId, String filePath)
{
 
XmlDocument Doc = new XmlDocument();
//load the entire document into memory
Doc.Load(filePath);
StringBuilder CustomerName = new StringBuilder(); //local variable
//stores last name and first name
XmlNode RootNode = Doc.DocumentElement;
XmlNode ResultNode = 
RootNode.SelectSingleNode("Customer[@id=" + "'" + customerId + "'" + "]");
if (ResultNode != null)
{
        //read the last name
        CustomerName.Append(ResultNode.SelectSingleNode("LastName").InnerText);
        //append space in between last and first name
        CustomerName.Append(" ");
        //append first name
        CustomerName.Append(ResultNode.SelectSingleNode("FirstName").InnerText);
}
//return customer name formatted as last name first name
return CustomerName.ToString();
}
}
}

Another Concrete Strategy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace StrategyPatternConsoleApplication
{
//this is another concrete strategy
//that reads an xml file sequentially
//may be suitable for large files
//not suitable for loading into memory
public class SequentialSearchXmlFileStrategy : ISearchXmlFileStrategy
 
{
///
 
/// Invokes strategy interface method
///
 
///Customer identifier ///Xml file name with path /// Customer name
public string GetCustomerNameByCustomerID(String customerId, String filePath)
{
XmlReader Reader = XmlReader.Create(filePath);
//local variable stores last name and first name
StringBuilder CustomerName = new StringBuilder(); //local variable
 
while (Reader.Read()) //read the xml file
{
if (Reader.IsStartElement()) //check if its starting element
{
var attr = Reader["id"]; //get the id attribute
//if attribute matches input customer id
if (attr != null && attr == customerId)
{
//move to last name element
if (Reader.ReadToFollowing("LastName"))
{
Reader.Read(); //read last name
//append the last name value
CustomerName.Append(Reader.Value);
}
 
if (Reader.ReadToFollowing("FirstName"))//move to first name element
{
Reader.Read(); //read first name
//append space between last name and first name
CustomerName.Append(" ");
//append the first name value
CustomerName.Append(Reader.Value);
break; //found record get out of loop
}
}
}
}
 
Reader.Close(); //close the reader
//return the formatted full name
return CustomerName.ToString();
}
}
}

Context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StrategyPatternConsoleApplication
{
//this is the context class
public class CustomerFinder
{
//holds a reference to the strategy
ISearchXmlFileStrategy _strategy = null;
 
///
 
/// Strategy setter
///
 
///The concrete strategy public void SetStrategy(ISearchXmlFileStrategy strategy)
{
_strategy = strategy;
}
 
//invoke strategy method
///
 
/// Invokes strategy interface method
///
 
///Customer identifier ///Xml file name with path /// Last name and first name as string
public String GetCustomerNamebyId(String customerId, String filePath)
{
return _strategy.GetCustomerNameByCustomerID(customerId, filePath);
}
}
}

Client:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace StrategyPatternConsoleApplication
{
class Program
{
///
 
/// Main Method - entry point to the console application
///
 
///Command Line arguments static void Main(string[] args)
{
 
Console.WriteLine("Please supply value of customer id");
String Id = Console.ReadLine();
ISearchXmlFileStrategy Strategy = new MemorySearchXmlFileStrategy();
CustomerFinder Context = new CustomerFinder();
Context.SetStrategy(Strategy);
String CustomerName = Context.GetCustomerNamebyId(Id, "C:\\Code\\StrategyPatternSolution\\CustomerData.xml");
//display result
if (String.IsNullOrEmpty(CustomerName))
{
Console.WriteLine("No Customer Found");
}
else
{
Console.WriteLine(CustomerName);
}
Console.WriteLine("Press any key to exit...");
//keep the console window open till the user presses any key
Console.ReadKey();
 
}
}
}

All other details on the Strategy Design Pattern are included in this video. I’d love you get your feedback and would also like to know how you have applied this design pattern.

Singleton Design Pattern

Singleton Design Pattern is one of the simplest and commonly used design patterns in object oriented design. Implementation of singleton classes ensures that only one instance of a class can be created. Please check out my latest video on this design pattern.

All the details are in the video. This blog post reiterates a few concepts that are discussed in this video and also includes source code that is used in the video.

Firstly, why does one need a singleton class? If an instance of a class does not hold any state that makes it distinguishable from other instances, that class becomes a candidate for Singleton. This becomes compelling in situations where class instantiation is a costly process. In general, I prefer to keep my controller classes stateless and those are generally declared singleton. There are posts on the internet that advocate static classes in place of singleton. My personal opinion is that static classes are easier to implement but static classes and methods have other shortcomings and that is why my preference is still singleton over static. This discussion is out of scope of this post and so I will cover my opinion in another post.

How do you make a class singleton?

a. Make it’s constructor private

b. Expose it’s only instance via a static property

c. Implement the ICloneable interface and throw an exception in the Clone method. This ensures that another program cannot create multiple instances of this program by calling ClassName.SingletonInstance.Clone().

Even though steps a – c appear fairly standard and easy to implement, there is another concern here which causes Singleton implementation to be problematic – thread safety.

In the YouTube video, I have taken the example of a “global setting” class that stores global settings for an application that are initialized once and never updated as long as the application runs. This is the implementation of a singleton class.

public class GlobalSettings: ICloneable
{
//the only instance of this class is created just once
private static readonly GlobalSettings SingletonInstance
= new GlobalSettings();
 
// private constructor
private GlobalSettings()
{
Console.WriteLine("constructor of GlobalSettings..");
}
 
// Exposes the only instance
public static GlobalSettings Instance()
{
return SingletonInstance;
}
// this is a sample setting value
public String SomeSetting()
{
return "I am Global Settings";
}
 
// Throws exception if any program tries to create another
// instance by cloning
public object Clone()
{
throw new ArgumentException("cannot clone this object");
}
} //end of class

To call a method on the singleton instance, a client program needs to use this expression. I have taken the example of the instance method called “SomeSetting”. Any instance method or property could be invoked in the same way as described below.

GlobalSettings.Instance().SomeSetting();

Please note that the class implements the ICloneable interface. So if another program tries to create another instance of this class by invoking code like shown below, they will get an exception.

GlobalSettings.Instance().Clone()

Hope you liked this post and video. Your feedback, as always, is valuable to me. Also, I’d like to hear from you how you implemented Singleton or the reasons why you do not use Singleton.

 

Abstract Factory Design Pattern

A factory is an object that produces something. In the world of software design, you need a factory object to create a “product” object so you can decouple the logic of the product’s creation from the objects that use that product. The product and its factory are naturally coupled and the logic of creating a product is centralized in the factory. Abstract Factory Design Pattern is a great way of implementing factories. Each factory can produce different families of products. And there can be more than one factory. Two factories can produce same family of products.

I was trying to implement something that is easy to related to and comprehend. So I took an example that involves two factory objects – Honda and Toyota. Each factory can produce two types of products – one car and one aircraft. And the entire object interaction is initiated via a simple client class. The cars expose a ‘drive’ behavior whereas the aircrafts expose a “fly” behavior. All the coding work was using the Visual Studio 2015 Integrated Development Environment and c# programming language.

I have uploaded two videos on the Abstract Factory. The first video mainly focuses on the class diagram of the prototype.

Abstract Factory Design Pattern (Part 1):

The second video does a walkthrough of the implementation. I have tried to create code “on the fly” so I can do a slow walk-through of the design and the code.

Abstract Factory Design Pattern (Part 2):

All the details are in the two videos. Hope you like the videos. If you have any questions, concerns or comments, please feel free to post those in the comments area. Also, I’d like to hear from your a scenarios where you used the concrete factory pattern or the abstract factory pattern. This is part of a series of posts on different design patterns and I’ll post several videos in the near future.

Template Method Design Pattern

Please check out my new video on the Template Method Design Pattern:

This post complements the video tutorial by adding the source code used in the video and also provides some additional information.

As per Wikipedia, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.

Let me explain the Template Design Pattern first and then we will revisit the definition. Lets assume that we are implementing an algorithm that has three steps that are executed sequentially. There is a “main” method invokes the three sub steps in the right sequence. The “main” method is called the template method and is what is invoked to execute the algorithm. The idea here is that we cannot change sequence of the three steps but what happens in these steps can be overridden or implemented differently by different classes. So the main/template method and the three methods that implement the three sub steps can be defined in a class. The three steps can be overridden in a sub class but the algorithm would still be executed from the parent class’s template method. The parent class can be declared as abstract that will force the consumers of this algorithm to always use a subclass. But the template method will be available by inheritance to each sub class.

In our prototype, the algorithm is the sequence of steps to register a student. The three steps are:
1. VerifyPrerequisites (check if the student meets the required pre-requisites for a course)
2. ProcessPayment (process course fee if the student meets prerequisites)
3. SendNotification (Send a notification to the student to confirm their registration if payment is processed successfully)

The main/template method is defined as RegisterStudent and it invokes steps 1-3 in the correct order. Lets take a look at the parent class. In our case, steps 1 and 3 have to be overridden by a sub class. But step 2 is implemented in the parent class because the ProcessPayment step is expected to to be common to all sub classes of CourseRegistrationHelper.

 public abstract class CourseRegistrationHelper
    {
        //template method
        public void RegisterStudent()
        {
            VerifyPrerequisites(); //step 1
            ProcessPayment(); //step 2
            SendNotification(); //step 3
        }
 
        //must be overridden by sub classes
        //this is step 1
        protected abstract void VerifyPrerequisites();
        //default implementation of this step is provided
        //this is step 2
        protected void ProcessPayment()
        {
            Console.WriteLine("Processing Payment the generic way");
        }
 
        //must be overridden by sub classes
        //this is step 3
        protected abstract void SendNotification();
    }

Two universities implement this abstract class in two different ways. The implementation is methods in the entire prototype is trivial but the idea here is to understand the structure of the Template Method Design Pattern.

This is the way University A implements this.

public class UniversityACourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate transcript");
        }
 
        //step 3
        protected override void SendNotification()
        {
            Console.WriteLine("Send a letter");
        }
    }

This is the way University B implements this:

 public class UniversityBCourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate university records");
        }
 
        //step 3
        protected override void SendNotification()
        {
            Console.WriteLine("Send email");
        }
    }

Now we can invoke the two algorithms in a c# console application.

class Program
    {
        static void Main(string[] args)
        {
            var HelperA = new UniversityACourseRegistrationHelper();
            //invoke template method
            HelperA.RegisterStudent();
 
            var HelperB = new UniversityBCourseRegistrationHelper();
            //invoke template method
            HelperB.RegisterStudent();
 
            Console.WriteLine("Press any key to close this window...");
            //wait for user to input a key
            Console.ReadKey();
        }
    }

The output looks like this:

Validate transcript Processing Payment the generic way Send a letter Validate university records Processing Payment the generic way Send email Press any key to close this window...

The template method RegisterStudent is available to both UniversityACourseRegistrationHelper and UniversityBCourseRegistrationHelper by inheritance but steps 1 and 3 are overridden by each class. But when RegisterStudent is invoked on either class, step 2 (ProcessPayment) is executed because its implemented in the parent class. This makes it flexible for us to implement a step in the algorithm either in the parent class or in the derived class. Can we have the flexibility to provide a ‘default’ implementation of a step in the parent class and override the step in a sub class if necessary? Yes, absolutely.

Lets tweak the parent class slightly and make the ProcessPayment method virtual (overridable in a sub class).

 protected virtual void ProcessPayment()

Now lets override this method implementation in the UniversityACourseRegistrationHelper like this:

    public class UniversityACourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate transcript");
        }
 
        //step 2
        protected override void ProcessPayment()
        {
            Console.WriteLine("Processing payment University A way");
        }
 
 
        //step 3
        protected override void SendNotification()
        {
 
            Console.WriteLine("Send a letter");
        }
    }

Now the output of this program will look like this:

Please note that UniversityBCourseRegistrationHelper is still using the default implementation of ProcessPayment. But all sub classes have the flexibility of either using the default implementation in the parent class or provide it’s own implementation.

Those steps that are different for each concrete implementation in a sub class must be declared as abstract so each subclass will have to provide an implementation.

Lets revisit the Wikipedia definition. The ‘program skeleton’ on the Wikipedia page is defined in the RegisterStudent template method and that cannot be changed. But the individual steps are deferred to a subclass (like UniversityACourseRegistrationHelper). The individual steps in our case are VerifyPrerequisites, ProcessPayment and SendNotification.

The Wikipedia link has an excellent example in multiple programming languages and can be viewed here.

Hope you liked this post and the video. Your feedback is valuable to me. Also, i’d like to hear your experience with the Template Method Design Pattern.

Command Design Pattern

My new video on the command design pattern is online at:

Introduction

Any object oriented software operates on interaction of various software components called objects. A typical interaction between two objects is a “client-server” interaction where one object sends a request and the other object processes the request and returns a response. The command design pattern provides a way for the client to encapsulate each request as an object (command) and submit each such request object to a another object called the invoker.

Key Features of the Command Design Pattern:

  1. All the invoker knows is that it holds a collection of commands and it can execute those commands immediately or later. Also, the invoker does not know the details of what each command does.
  2. Since all commands implement a common interface, the invoker can execute those via the common interface and that way its not coupled to any concrete command and the details of what each command does.
  3. Another key player in this type of interaction is the receiver object. Each command encapsulates its receiver object. And there can be more than one receiver involved in the command pattern object interaction if necessary.
  4. A command is initiated by the invoker object but it is the receiver object that eventually processes the command.
  5. A command object is self-contained – it knows its receiver and all the data that is needed to execute that command. So a command can be persisted in a  “queue” and executed later.

So one advantage of using command pattern is that creation of commands is independent of when it is executed. Also, the commands can be grouped in multiple groups and executed in a batch like a macro. So if we were implementing an airplane’s navigation system, all the commands for a plane to depart (taxi to runway, takeoff, adjust altitude and speed to go up to 10000 feet) and arrive (reduce speed and altitude to be able to land, land and taxi to gate) can be two sets of commands. Each set is basically like a macro and can be executed at different points of time by the invoker which is the cockpit dashboard. Another advantage of the command design pattern is that the commands can be executed as a transaction where either all commands are executed or none of these are executed. In such as case, the command interface could provide two stubs – execute and undo. The ‘undo’ operation would reverse all the actions of a command. So if the invoker encounters an error, it would execute undo operation on all commands executed to that point and this will essentially be an “all or nothing” transnational operation.

The video link at the beginning of this post includes all the details of the command design pattern with an implementation of a logging framework. The source code is provided below.

Abstract Command:

//common contract for all logger commands
//this is the abstract command
public interface ILogMessageCommand
{
  void LogMessage();
}

Concrete Command for File Logging:

//concrete command
public class LogMessagetoFileCommand: ILogMessageCommand
{
//receiver
FileLog _fileLog = null;
//the message to be logged
String _message = null;
 
public LogMessagetoFileCommand(FileLog filelog, String message)
{
_fileLog = filelog;
_message = message;
}
 
public void LogMessage()
{
//interact with the receiver to process the command
_fileLog.LogMessage(_message);
}
 
}

Concrete Command for Database Logging:

public class LogMessagetoDatabaseCommand : ILogMessageCommand
{
   DatabaseLog _dbLog = null; //receiver
   String _message = null; //the message to be logged
 
  public LogMessagetoDatabaseCommand(DatabaseLog dblog, 
          String message)
   {
    _dbLog = dblog;
    _message = message;
   }
 
public void LogMessage()
   {
   //interact with the receiver to process the command
    _dbLog.LogMessage(_message);
   }
}

FileLog Receiver:

public class FileLog
{
   //singleton instance
   public static readonly FileLog Instance = new FileLog();
  //constructor should be private for singleton implementation
    private FileLog()
    {
    }
   //read the log file path from the application configuration file
    String _filePath = 
    ConfigurationManager.AppSettings["LogFilePath"].ToString();
   //write the log message to the file
   public void LogMessage(String message)
   {
    Console.WriteLine("Writing to a log file");
    string[] AllMessages = new string[] {message};
    File.WriteAllLines(_filePath, AllMessages);
   }
}

Database Log Receiver:

public class DatabaseLog
   {
    //singleton instance
     public static readonly DatabaseLog Instance 
     = new DatabaseLog();
   //constructor should be private for singleton implementation
    private DatabaseLog()
    {
    }
//read the connection string from the application configuration file
   String _connectionString 
   = ConfigurationManager.ConnectionStrings["LogDatabase"].ToString();
 
    //log the message to a database table
    //not implemented yet
   public void LogMessage(String message)
   {
     Console.WriteLine("Writing to a logging database");
     try
     {
      IDbConnection Conn = new SqlConnection(_connectionString);
      IDbCommand Cmd = new SqlCommand();
      Cmd.CommandType = CommandType.StoredProcedure;
      //stored procedure name for logging
      Cmd.CommandText = "usp_AddText";
 
      Cmd.Parameters.Add(new SqlParameter("@message", message)); 
     //Conn.Open();
     //Cmd.ExecuteNonQuery(); not implemented
     //Conn.Close();
     }
    catch (Exception ex)
     {
     //TODO: handle exception
     }
   }
}

Invoker:

public class LoggerFramework
{
   List _allCommands = null;
 
   //receive all commands
   public LoggerFramework(List allCommands)
    {
     _allCommands = allCommands;
    }
 
   //invoker them one by one
   //does not know concrete commands
   public void LogMessages()
   {
    foreach (ILogMessageCommand command in _allCommands)
    {
     command.LogMessage();
    }
  }
}

Invoker:

public class LoggerFramework
{
   List _allCommands = null;</code>
 
   //receive all commands
   public LoggerFramework(List allCommands)
   {
    _allCommands = allCommands;
   }
 
   //invoker them one by one
   //does not know concrete commands
    public void LogMessages()
    {
     foreach (ILogMessageCommand command in _allCommands)
    {
      command.LogMessage();
    }
  }
}

Client:

//create concrete command objects
//create log message to file command 
//and set the receiver and the message on it
ILogMessageCommand LogMessageToFileCommand = 
new LogMessagetoFileCommand(FileLog.Instance, "Message for file");
//create log message to database command and 
//set the receiver and the message on it
ILogMessageCommand LogMessagetoDbCommand = 
new LogMessagetoDatabaseCommand(DatabaseLog.Instance, 
"Message for database");
 
//create a list of commands
List _allCommands = new List();
_allCommands.Add(LogMessageToFileCommand);
_allCommands.Add(LogMessagetoDbCommand);
 
//create the invoker and set the commands on it
LoggerFramework framework = new LoggerFramework(_allCommands);
//request the invoker to execute all commands
framework.LogMessages();
 
//display a message for the user so thay can quit the program
Console.WriteLine("Press any key to quit.");
 
//wait for user input before console window is closed
Console.ReadKey();

Sorry this turned out to be a long post partly due to the inclusion of the source code. I’d love to hear from you how you have implemented the command design pattern. Any other feedback is always appreciated.

Proxy Design Pattern

Proxy is a very simple yet very powerful design pattern that is used a lot in software design. In fact, many people use Proxy Design Pattern but do not use the nomenclature. Please check out my video on the Proxy Design Pattern.

This post contains some additional information and source code of the applications shown in the video.

When we think of the Proxy Design Pattern, we think of a Proxy object that works like a “middleman”. This object sits in between the client object and the service object (called Real Subject in Proxy Design Pattern lingo), intercepts messages between the client and the service objects and provides additional functionality. The additional functionality could be one or more of the following:
1. Simply the communication between the the client and the service
2. Protect the service object from unauthorized access.
3. Do some additional data processing before the message is handed over to the service. The proxy object could do some data processing when the information is flowing back from the service to the client object.
4. Defer the instantiation of the service object as much as possible if the service object instantiation is costly.

And list of Proxy Object functionality is not confined to the bullets listed above. Any time we need a “middleman” to do any type of additional work, we could include a proxy object.

The class diagram of the Proxy Design Pattern is:

Proxy Design Pattern Class Diagram

 

The Proxy and the Real Subject are expected to provide a common interface to the client object. This is possible because their classes implement a common interface which is called AbstractSubject in the class diagram.

Wikipedia covers three usage scenarios of Proxy objects here.

The YouTube video covers the three usage scenarios described on the Wikipedia page. The scenarios are:
a. Remote Proxy – This proxy is useful when the client and the real subject reside in different address spaces. The service object in our example is a web service object hosted by United Postal Service (UPS). The methods on this remote service are invoked by the client object via a proxy that is generated by Visual Studio. To the client object, this service appears to be a local object and the service invocation appears just a local method invocation. But this proxy object (service reference) works with the .net runtime to convert these method invocations to web requests on the UPS Service object and so the service reference object works like a remote proxy. This video just shows how to create this service reference (remote proxy). If you are interested in using the UPS API for address validation and package tracking, it is discussed here and here.

b. Protection Proxy – This proxy prevents unauthorized access to an object. In our example, a protection proxy checks the security principal of the logged in user in a windows desktop application and allows or prohibits access to the real subject if the logged in user is in the administrators security group. This is the source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
 
namespace ProxyDemoConsoleApplication
{
    class Proxy
    {
        public void DoSomething()
        {
            //code snippet in protection proxy method
            //get security principal associated with the
            //logged in user
 
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
 
            //check user access
            //is the user admin
            if (principal.IsInRole("Administrators"))
                RealSubject = new RealSubject();
                //invoke real subject method
                RealSubject.DoSomething();
            else  //if not, throw an exception
            {
                throw new SecurityException("Cannot access this object");
            }
 
        }
    }
}

c. Virtual Proxy – This proxy defers the instantiation of a real subject because the instantiation process is costly. The example in the video is a Customer Account class which holds a collection of Transactions. When you create Customer Account Class Instance, all the transactions on the customer account ever since it was opened is loaded an attribute on the object. The ShowBalance method on the class sums up the amounts associated with all transactions. This is the Customer Account class.

public class CustomerAccount: ICustomerAccount
    {
 
        IList AllTransactions = new List();
        String _customerId = null;
 
            public CustomerAccount(String customerId) {
 
            _customerId = customerId;
 
            //costly operation - load all transactions since the account was opened
            //.........
            //.........
 
        }
 
        public Decimal ShowBalance()
        {
            Decimal Balance = 0;
 
            //loop through each transaction and add the amount to determine total balance
            foreach(Transaction tr in AllTransactions)
            {
                Balance += tr.Amount;
            }
 
            return Balance;
        }
 
    }

The details of the Transaction object are not very relevant but the code is provided for the sake of completion.

    //abstract subject
    public interface ICustomerAccount
    {
        Decimal ShowBalance();
    }

Both Real Subject (CustomerAccount) and Proxy (ProxyCustomerAccount) implement a common interface.

public  class Transaction
    {
        DateTime _transactionDate; //date the transaction was done
        Decimal _amount; //transaction amount
        public Transaction(DateTime transactionDate, Decimal amount)
        {
            _transactionDate = transactionDate;
            _amount = amount;
       }
        public Decimal Amount
        {
            get
            {
                return _amount;
            }
        }
    }

The Proxy object’s constructor does not instantiate the real subject immediately. It creates the real subject only when the ShowBalance method is invoked. This is the code:

    //virtual proxy
    public class CustomerAccountProxy : ICustomerAccount
    {
 
        CustomerAccount realSubject = null;
        String customerID;
 
        public CustomerAccountProxy(String custId)
        {
            //store the customer ID as a private attribute
            customerID = custId;
            //defer the creation of customer account until
            //ShowBalance is called
            //do nothing for the time being
        }
 
        public Decimal ShowBalance()
        {
            //now create the real subject because the balance
            //cannot be determined until the real subject is loaded
            realSubject = new CustomerAccount(customerID);
            return realSubject.ShowBalance();
 
        }
    }

So the Client Object, which is a console application’s main method, can call methods on the Real Subject via the Proxy Object like this.

class Program
    {
        public static void Main()
        {
            //client code
            CustomerAccountProxy Proxy = new CustomerAccountProxy("12345678");
            //do some work
            //...
            //...
            //...
            //the real subject gets created when the next line is executed
            Console.WriteLine(Proxy.ShowBalance());
            Console.ReadKey();
        }
    }

All code is c# and targets .Net Framework 4.5. I’d love to hear from you on your experience with the Proxy Design Pattern and also your feedback on this post and the YouTube Video.

Facade Design Pattern

Facade Design Pattern is one of the simplest design patterns that is used frequently in software design. As per Wikipedia, the word ‘Facade’ is derived from the building architecture term Facade which is one exterior side of a building. This is the “interface” to the building. In the same way, a Facade is an interface to a larger body of code. More details are available at this Wikipedia link.

Please check out my new video on the Facade Design Pattern.

This video provides a simple example from real life where an individual acts like a “Facade”. A surveyor has a questionnaire that needs the following information:
1. Age Range of the person filling the survey
2. Income Range of the person filling the survey
3. Name of their favorite cafe in the city.

Lets assume that the person who wants to conduct this survey needs to visit an office building and collect this information from all the employees working in that building. One way to do this would be to speak to each employee and collect this data. This is, of course, assuming they will allow the survey person to speak to each employee. Another option is to speak to the location supervisor and hand over these survey to that person. The supervisor would talk to each employee, collect this information and hand over the responses on a stack of paper or electronic document to the survey person. This greatly simplifies the interaction between the survey person and the employees in that building. And in this case, the supervisor is the ‘facade’ to the employees in the building. Please note that the total number of interactions for data collection does not change but the interface between the survey person and the the employees is certainly simplified. This is application of the “Facade” pattern in terms of human interaction.

If we extend this model to software design, we could consider this scenario as an example. We have a class library called GeographicalServicesLibrary. The purpose of this library is to provide the distance between two addresses. This class library consists of the following classes:

a. Address Validator – This class exposes a solitary method that takes an address as a string parameter and returns a properly formatted address (format defined by postal service) to the caller. If the address is invalid, the returned string would contain an error code.

b. Geocode Helper – This class exposes a method that takes a properly formatted address and returns a Point object that contains the coordinates of that address (latitude and longitude).

c. Distance Calculator – This class provides a method that calculates the distance between two Point objects.

In order to calculate the distance between two addresses, the client object has to perform the following calls to this class library:

i. Call the Address Validator method and validate the first address.

ii. Call the Address Validator method and validate the second address.

iii. Call the Geocode Helper method and get the coordinates of the first address.

iv. Call the Geocode Helper method and get the coordinates of the second address.

v. Call Distance Calculator method and pass the coordinates of the two addresses and get the distance between the two coordinates.

This is shown in the c# code below:

//validate the first address
String ValidatedAddress1 = AddressValidatorObject.ValidateAddress(Address1);
//validate the second address
String ValidatedAddress2 = AddressValidatorObject.ValidateAddress(Address2);
//get the coordinates of the first address
Point p1 = GeocodeHelperObject.GetGeoCode(ValidatedAddress1);
//get the coordinates of the second address
Point p2 = GeocodeHelperObject.GetGeoCode(ValidatedAddress2);
//calculate the distance between the two addresses
Double Distance = DistanceCalculatorObject.GetDistance(p1, p2);

The total number of interactions between the client object and the class library members can be significantly reduced by introducing a “facade” object called the Geographical Service Facade. This class could expose a method that would take the two addresses as input parameters and return the distance between the two addresses. This facade object could interact with the members of this class library to get the desired output (distance between two addresses). The Facade class reduces the dependencies between the client and the class library members because only one class (the Facade) has dependencies on the class library. This is specially important if the class library is a third party library that may get replaced later. If a replacement is needed, only the one call in the Facade needs to change.

This is shown in the c# code below:

//calculate the distance between two addresses
Double Distance = 
GeographicalServicesFacadeObject.CalculateDistance(Address1, Address2)

Also, you could argue that the class library was poorly designed. If the goal of the class Library is the return the distance between two addresses, all it had to do was to keep expose this functionality perhaps as a Facade object. And the library could hide the three classes –  Address Validator, Geocode Helper and Distance Calculator. This brings forward another advantage of the Facade Pattern that it simplifies interactions with a poorly designed library. In general, Facade Pattern makes a library or any collection of components easy to use and test. This is because the interface to the components is greatly simplified due to the introduction of the Facade object. Please note that Facade does not necessarily has to hide a large collection of components or a class library. It could just be introduced to simply interactions among any collection of objects.

Thanks for visiting this site and reading this post. Hope you liked the explanation. I’d love to get your feedback on this post and also your experience with the Facade Design Pattern.