Sunday, February 7, 2016

Design Patterns : Facade Pattern

You may also like to see:

Facade design pattern is a structural design pattern. Word facade means 'a deceptive outward appearance'. As facade design pattern hides all the complexities of one or many sub-systems and provides a clean, easy to use facade interface.

We can create multiple Facade interfaces by grouping relevant sub-system in particular class. The client will communicate these facades instead of complex individual subsystems.

Facade Design Pattern - Class Diagram

Implementation

Let's implement a facade pattern on an e-commerce site. We are going to create an online shopping system in which user selects an item from a catalog and place an order. Let's see its code

public class Inventory 
{
    public bool IsItemAvailable(String itemId) 
    {
       return "Item details";
    }
}

public class Payment 
{
    public String Pay(String itemId,Paypal paypal)
    {
       return "Charge for items";
    }
}

public class Shipping 
{
    public String ShipOrder(String itemId,Address shipmentAddress) 
    {
       return "Ship items to address";
    }
}

public class OrderFacade 
{
    // composed of all Order related sub-systems
    Payment _Payment;
    Inventory _Inventory;
    Inventory _Shipping;

    public void OrderFacade()
    {
        _Payment = new Payment();
        _Inventory = new Inventory();
        _Shipping = new Shipping();
    }

    public void PlaceOrder(String itemId,string creditCard,string shipmentAddress) 
    {
      // check if item is available 
      if(!_Inventory.IsItemAvailable(itemId)) return "Item Not Available";
      // charge for item price
      _Payment.Pay(itemId, new Paypal(creditCard));
      // ship order to customer
      _Shipping.ShipOrder(itemId,shipmentAddress) 
    }
}

public class Client 
{
    public static void main()
    {
       OrderFacade orderFacade = new OrderFacade();
       orderFacade.PlaceOrder("1234", "321546", "23-B Frim Road, Moscow");         
    }
}


As you have seen OrderFacade has encapsulated all the order-related activities and now client just has single point to communicate instead of invoking each sub-system individually. OrderFacade will delegate relevant sub-system and will complete the client request.

Facade pattern provides an interface which is easy to use for a client by hiding many interfaces. This pattern is actually straightforward but it is quite powerful. It allows us to make our system loosely coupled. There is a design principle Least Knowledge which guide us to have fewer dependencies between objects which mean objects should not be tightly coupled otherwise it would be difficult to manage.

Using Facade pattern as we know we have an interface which is responsible for communicating between the objects so it actually allows us to have fewer dependencies within objects. It has many advantages for instance in our example of online shopping system if our payment system is completely independent we can easily change it anytime without affecting the client.

Conclusion


Facade design pattern is a structural pattern which makes design easy by allowing to make a system less tightly coupled and provide an interface to the client which is clean and easy to use by hiding all complexities of sub-systems.


You may also like to see:

Friday, February 5, 2016

Design Patterns : Adapter Pattern - Be Adaptive

You may also like to see:

Adapter pattern works as a bridge between two separate objects. It converts interface of a class into another interface which is required. Adapter pattern lets different classes work together that could not otherwise due to the different interface of each class.

Understanding Adapter pattern is not that difficult because it works same as we see an adapter in the real world. The simplest example is AC power adapter which we use for cell-phone, laptop chargers. Electricity at home socket is 220 volts (or 110 volts) but our cell phone needs 5-12 volts so we need an adapter which should convert the power to required range.

Adapter in Programming


Let's see a real world example for Adapter pattern. Information sharing system's team is working on a system which uses social networks sites to share the content. The team has designed an interface which is implemented by Facebook, Twitter, and Linkedin classes. The system is using this interface to switch between these sites and share the content. Developers have to spend a lot of time in implementing these network site's public APIs in these classes and make system bug free and tested.


Here is code implementation of the system.
public interface ISocialNetworks
{
    bool Login(string username, string password);
    bool Share(string content);
}

public class Facebook: ISocialNetworks
{    
    public bool Login(string username, string password)
    {
       //Login Using Facebook API
    }

    public bool Share(string content)
    {
       //Share Using Facebook API
    }
}

public class Twitter: ISocialNetworks
{    
    public bool Login(string username, string password)
    {
       //Login Using Twitter API
    }

    public bool Share(string content)
    {
       //Share Using Twitter API
    }
}

//similarly for Linkedin


Everything was working fine until client wanted Google+ also in the list and team know to implement the same interface you have to understand APIs and have to put a huge effort in implementations. But you found that Google+ has already developed a library so you downloaded that library and try to integrate into your system.


There is a little problem Google+ developers have implemented their own interface which is not compatible with our information sharing system. Here is the code:
public interface IGoogleSocialNetworks
{
    bool Authenticate(string username, string password);
    bool Post(string content);
}

public class GooglePlus: IGoogleSocialNetworks
{    
    public bool Authenticate(string username, string password)
    {
       //Login Using Google API
    }

    public bool Post(string content)
    {
       //Share Using Google API
    }
}


Now here comes the adapter which will convert interface of Google+ library to the interface of desired system interface i.e, ISocialNetworks. Let's see its code implementation
public class GoogleNetworksAdapter: ISocialNetworks
{
    GooglePlus GoogleLibrary;

    public void GoogleNetworksAdapter (GooglePlus googleLibrary)
    {
       this.GoogleLibrary = googleLibrary;
    }

    public bool Login(string username, string password)
    {
       GoogleLibrary.Authenticate(username, password);
    }

    public bool Share(string content)
    {
       GoogleLibrary.Post(content);
    }
}

Let see design diagram after implementing adapter pattern



Now since Google+ adapter has the same interface as our other Social Networks i.e, ISocialNetworks so it can be use in system easily. Here is how client uses the adapter:
  1. Client make a request to Adapter class (GoogleAdapter) for a method of target interface (ISocialNetworks) e.g, Login
  2. Adapter class translate that request to adapted object method (IGoogleSocialNetwoks) e,g, Authenticate and return response
  3. Client receive the response without realizing that Adapter converted its request to another form.

Here is the class diagram of Adapter Pattern


Adapter pattern uses other good practices of Object Oriented for example object composition in Adapter class to wrap adapted functionalities in target interface. Another advantage of using this object composition is that this adapter can be used with any child class that inherits this Adapted class.


Special Scenario

We have seen a simple example in which all the methods of target interface were available in adapted class. What if there is a method in target interface which is not available in adapted class? In that case adapter pattern is not perfect to use because we have to throw a NotImplementedException. So the client will have to watch out for possible exceptions from the adapter class. The Adapter class should be well documented to reduce the chance of leaving unhandled exception at the client end.


You may also like to see:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,