Friday, February 28, 2014

Structural Design Patterns: Facade Design Pattern




Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. 
The face hides all the complexities of the building and displays a friendly face.

Problem 

A segment of the client community needs a simplified interface to the overall functionality of a complex subsystem. 

 Intent

  • Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
  • Wrap a complicated subsystem with a simpler interface.


GoF definition for facade design pattern is, “Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.”
It also promotes decoupling the subsystem from its potentially many clients. On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that "power users" may need.
These two patterns work in much the same way, but they have different purposes. The  Adapter pattern adapts code to work with other code. But the Facade pattern gives you a wrapper that makes the original code easier to deal with.
Think of a component that solves a complex business problem. That component may expose lot of interfaces to interact with it. To complete a process flow we may have to interact with multiple interfaces.
To simplify that interaction process, we introduce facade layer. Facade exposes a simplified interface (in this case a single interface to perform that multi-step process) and internally it interacts with those components and gets the job done for you. It can be taken as one level of abstraction over an existing layer.

When to use Façade Pattern?
 Layering: Facade pattern can be used in JEE applications for creating a layer to abstract and unify the related interfaces in the application. Use of a facade will define an entry point to each subsystem level and thus make them communicate only through their facades; this can simplify the dependencies between them.

Façade makes the API and libraries easier to use which is good for maintenance and readability. It can also collate and abstract various poorly designed APIs with a single simplified API.

It also reduces dependencies of the external code on the inner working of the libraries and thus providing flexibility.


Example 1
 A very good example is the startup of a computer. When a computer starts up, it involves the work of CPU, memory, hard drive, etc. To make it easy to use for users, we can add a facade which wrap the complexity of the task, and provide one simple interface instead.


1:  public class CPU {  
2:       public void processData(){  
3:            System.out.println(" CPU initializing ");  
4:       } 


1:  public class Memory {  
2:    public void loadMemory(){  
3:         System.out.println(" Load Memory in the RAM ");  
4:    }  
5:  }  


1:  public class HardDrive {  
2:    public void readData(){  
3:         System.out.println(" Read Data from HDD ");  
4:    }  
5:  }  



There are different internal part which are required to make single unit for Computer.
1:  public class Computer {  
2:    private CPU cpu;  
3:    private HardDrive hdd;  
4:    private Memory mem;  
5:    public Computer() {  
6:      cpu = new CPU();  
7:      hdd = new HardDrive();  
8:      mem = new Memory();  
9:    }  
10:    public void run(){  
11:      cpu.processData();  
12:      mem.loadMemory();  
13:      hdd.readData();  
14:      System.out.println(" Computer Started ... Read to Use ");  
15:    }  
16:   }  
17:  }  



Example 2 : Order processing online website. The client has placed an order without having knowledge of how internal classes are functioning. Once the order is placed the façade class layer calls the methods of the subsystems like Inventory for inventory check and Payment for processing of the payment. After processing it returns the control to the client class with the confirmation about the order being processed.



1:  public class Inventory {  
2:    public String checkInventory(String OrderId) {  
3:      return "Inventory checked";  
4:    }  
5:  }  


1:  public class Payment {  
2:    public String deductPayment(String orderID) {  
3:      return "Payment deducted successfully";  
4:    }  
5:  } 


1:  public class OrderFacade {  
2:    private Payment pymt = new Payment();  
3:    private Inventory inventry = new Inventory();  
4:      public void placeOrder(String orderId) {  
5:          String step1 = inventry.checkInventory(orderId);  
6:       String step2 = pymt.deductPayment(orderId);  
7:       System.out.println("Following steps completed:" + step1 + " & " + step2);  
8:    }  
9:  }  


1:  public class Client {  
2:       public static void main(String args[]) {  
3:            OrderFacade orderFacade = new OrderFacade();  
4:            orderFacade.placeOrder("JavaHeadBook");  
5:            System.out.println("Order processing completed");  
6:       }  
7:  }  


Output of this program will be as below : 
 Following steps completed:Inventory checked & Payment deducted successfully
Order processing completed


3rd real time example


Similarly consider microwave oven, it consists of components like trasnformer, capacitor, magnetron, waveguide and some more. To perform an operation these different components needs to be activated in a sequence. Every components has different outputs and inputs. Imagine you will have separate external controller for all these components using which you will heat the food. It will be complicated and cumbersome.
In this scenario, oven provides you preprogrammed switches which can be considered as a facade. On click on of a single switch the job gets done. That single menu switch works as an abstraction layer between you and the internal components.


Interesting points:
Façade pattern might be confused with mediator pattern. Mediator also abstracts the functionality of the subsystem in similar manner to façade. However there is a subtle difference between both these patterns. In case of Mediator pattern the subsystem is aware of the mediator, however in case of Façade the subsystem does not know anything about the façade. It’s a one way communication from Façade to subsystem.


Façade used in Java API
javax.servlet.http.HttpSession
javax.servlet.http.HttpServletRequest
javax.servlet.http.HttpServletResponse
javax.faces.context.ExternalContext

Notes:
1)    the Façade pattern hides the complexities of system from the client and provides a simpler interface. Looking from other side, the facade also provides the implementation to be changed without affecting the client code.
2)    Usage:  make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).3)    Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one. 
    4)    Flyweight shows how to make lots of little objects; Facade shows how to make a single object represent an entire subsystem. 
    5)    Abstract Factory can be used as an alternative to Facade to hide platform-specific classes. 
    6)    Facade objects are often Singletons because only one Facade object is required. 
    7)    Adapter and Facade are both wrappers; but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects. 
    8)    Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communications between colleague objects. It routinely "adds value", and it is known/referenced by the colleague objects. In contrast, Facade defines a simpler interface to a subsystem, it doesn't add new functionality, and it is not known by the subsystem classes.
  Question: So the way to tell the difference between the Adapter pattern and the Facade pattern is that the Adapter wraps one class and the Facade may represent many classes?
Answer: No! Remember, the Adapter pattern changes the interface of one or more classes into one interface that a client is expecting. While most textbook examples show the adapter adapting one class, you may need to adapt many classes to provide the interface a client is coded to. Likewise, a Facade may provide a simplified interface to a single class with a very complex interface. The difference between the two is not in terms of how many classes they "wrap", it is in their intent
Drawbacks/Consequences:
  • One of the drawback is that the subsystem methods are connected to the Façade layer. If the structure of the subsystem changes then it will require subsequent change to the Façade layer and client methods

Summary of Facade Design Pattern

  • Facade provides a single interface.
  • Programmers comfort is a main purpose of facade.
  • Simplicity is the aim of facade pattern.
  • Facade design pattern is used for promoting subsystem independence and portability.
  • Subsystem may be dependent with one another. In such case, facade can act as a coordinator and decouple the dependencies between the subsystems.
Translating data to suit the interface of a subsystem is done by the facade 

No comments: