Facade Design Pattern

29/01/2012

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.”

How do we infer the above definition? 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.

Facade design pattern is one among the other design patterns that promote loose coupling. It emphasizes one more important aspect of design which is abstraction. By hiding the complexity behind it and exposing a simple interface it achieves abstraction.

Real World Examples for Facade Pattern

I wish to give you couple of real world examples. Lets take a car, starting a car involves multiple steps. Imagine how it would be if you had to adjust n number of valves and controllers. The facade you have got is just a key hole. On turn of a key it send instruction to multiple subsystems and executes a sequence of operation and completes the objective. All you know is a key turn which acts as a facade and simplifies your job.

Ads by Google

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.

These are realworld examples for facade design pattern. In software scenario, you can have interfaces which acts as a facade. Methods in these interfaces contains the interaction sequence, formatting and converting data for input for components. As such it will not hold the business logic.

UML Diagram for Facade Design Pattern

Common Mistakes while Implementing Facade Design Pattern

In my experience the common mistakes I have seen is,

  • just for the sake of introducing a facade layer developers tend to create additional classes. Layered architecture is good but assess the need for every layer. Just naming a class as ABCDFacade.java doesn’r really make it a facade.
  • Creating a java class and ‘forcing’ the UI to interact with other layers through it and calling it a facade layer is one more popular mistake. Facade layer should not be forced and its always optional. If the client wishes to interact with components directly it should be allowed to bypass the facade layer.
  • Methods in facade layer has only one or two lines which calls the other components. If facade is going to be so simple it invalidates its purpose and clients can directly do that by themselves.
  • A controller is not a facade.
  • Facade is ‘not’ a layer that imposes security and hides important data and implementation.
  • Don’t create a facade layer in advance. If you feel that in future the subsystem is going to evolve and become complicated to defend that do not create a stub class and name it a facade. After the subsystem has become complex you can implement the facade design pattern.
  • Subsystems are not aware of facade and there should be no reference for facade in subsystems.

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.

Facade Vs Mediator Design Pattern

Mediator design pattern may look very similar to facade design pattern in terms of abstraction. Mediator abstracts the functionality of the subsystems in this way it is similar to the facade pattern. In the implementation of mediator pattern, subsystem or peers components are aware of the mediator and that interact with it. In the case of facade pattern, subsystems are not aware of the existence of facade. Only facade talks to the subsystems.

Facade Design Pattern in Java API

ExternalContext behaves as a facade for performing cookie, session scope and similar operations. Underlying classes it uses are HttpSession, ServletContext, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse.

This Design Patterns tutorial was posted on 29/01/2012.
Ads by Google

121 comments on “Facade Design Pattern

  1. Good article man, good examples and key points.
    Keep it going ;)

  2. very nice article!
    It Consists all the things like common mistakes, api example and real world example.. :)

    Keep growing..

  3. Is facade is similar to the concept ” Code for interface not for implementation”

    • factory will return the object but in facade it is not

  4. Like your way of explanation with real world example. Nice article.

  5. your way of explanation and view is very nice. Please provide programmatic explanation.

  6. nicly explained but can any body give the code for the same

  7. @Ahmad, this is not an implementation of code for interface.

    I will try to add some code example soon.

  8. can we able to get…application codes…?
    in case if we want code for some module to design an application…in java…
    is there any link or site available which will help us in such case??

  9. Thanks for the above details. could you please explain JDO in java.

  10. Design Pattern are explained very clearly and pointed out key areas..thanks

  11. very nice article. IT will be more helpful if u add java code demonstrating FACADE

  12. nice examples giving clear roadmap of design pattern

  13. hi joe,
    it’s a nice article can u provide this with small example.

  14. Excellent!!

    Simple and relevant information.

  15. Very nice and well explained! Thanks!

  16. Got the concept clearly..but plz post a small scenario which uses struts2-jsps,tiles,facade,DVO,BO,DAO
    Its needed in business applications

  17. theory explaind well , but try to add some real time examples or atleast links to examples of ur own, which helps for beginners and those who are intrested in learning java.

    Regards
    Raj

  18. Good explanation with example. Thank You for your blogs.

  19. Nice examples and guidance to avoid mistakes!

  20. relevant, clear and cool explanation.
    Please add a code implementation.

  21. Hi Joe, Based on your explanation I have written a sample, can the following code be a facade example? Please reply…

    package scjp;

    interface Car{
    public void start();
    }

    class Start implements Car{
    @Override
    public void start() {
    PowerIgnition pi = new PowerIgnition();
    pi.startPowerIgnition();
    Fuel f = new Fuel();
    f.startFuelFlow();

    }
    }

    class PowerIgnition{

    public void startPowerIgnition() {
    System.out.println(“Power Ignited from Battery”);
    }
    }

    class Fuel{
    public void startFuelFlow() {
    System.out.println(“Fuel flow started”);
    }
    }

    public class TestFacadePattern {

    public static void main(String[] args) {
    Car car = new Start();
    car.start();
    }
    }
    # John Sambath – johnsambath@gmail.com #

    • Hi John,
      your example is good. But slight mistake though. Start cannot be a class . it is a verb and should be a method. rather you you have named it as CarFacade? for inheritance it should always pass ‘IS A’ test else it is wrong implementation of inheritance.

  22. I used facade for more than 1 yr, but today after reading this article many doubts got clarified. Thaks for such a lovely article.

  23. Good examples. In a typical 3 layer(presentation, service, dao)
    the business layer and the dao layer interfaces could be considered facades. Right?

    • Hi,

      nope. Since those are interfaces, and the facade is an implementation that uses other interfaces/implementations.

      Additionally it should only have an additional formatting logic. No complicated stuff in there like dao usage for instance (since that is a (business) service responsibility) .

  24. Please provide some java code example.

  25. Please provide me some simplejava code example.

  26. Thanks for the explanation and making it simple to understand the Design pattern.

  27. very good article. thank you very much for the effort but why there’s no implementation example?

  28. It’s really good explaining with examples

  29. wonderful explanation and nice example

  30. Good article but should provide some code showing the working example of Facade Design pattern…
    otherwise, theoretically it covers almost everything. :)

  31. It will be great help if code also provided

  32. Nice examples and metaphores but programmatically explaining will make life much more easier…anyways superb joe.:)

  33. Excellent article!!..Real world examples are good…

  34. thank you very much sir i have understand well about facade can u please provide me documentation

  35. can we say this facade as a front controller?

  36. Simple example and clear…Keep sharing :)

  37. Nice explanation sir… But i have few doubts regarding this…
    U said that facade provides a single interface .If my business layer consists of 10 classes n assume each class has 3 methods then for a good facade design pattern implementation which of the following approaches are good?
    1)Mentioning all these 30 methods in a single interface?
    or
    2)Defining one interface with 3 methods. The other 9 classes extends the class that implements the interface?

    Please give your valuable reply n allow me to get clarified on this concept.
    Thanks in advance….

    • Hi Divya,
      It is not good to expose single interface with all the methods. It makes your classes grow in size Just remember the SPR principle it says your class should have only one reason to change. in your case you will have multiple reasons to change. So back to your question, I would say it is none. Facade pattern widely in use in EJB’s where remote calls are always going to be expensive. let’s say client(read it has struts actions or servlets or web services) need to use multiple business services(updations, deltions, insertiions using different business services) since these service invocations are really costly in case of remote invocations . It is better to create Facade which can encapsulate these subsystem invocations so that client can make only one single call which reduces the complexity involved in the client rather exposes unified interfaces to other clients which needs similar functionality(web services, rest , swings).

      Hope it helps.

      • Thanks for pointing it. A minor correction, its Single Responsibility Principle (SRP). As per SRP, Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. Robert C. Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to change. (courtesy Wikipedia)

  38. Thanks Joe. I always try to brush up on the design patterns when there is a situation for a interview. Honestly never ever i came up with someone explaining these concepts as simple as you have explained out here. You are simply awsome. Thanks Again :)

    Sameer

  39. If sample/example code was also included it would be further more useful.

  40. Good Example. if you could attach the code for respective design pattern then, it would be realy good.

    • Sure Manoj, will write up some sample code and update the tutorial soon.

  41. I have a query here, suppose there are 5 interfaces and each class implement only those which are needed, but if I create one common interface then implementing class will have to add method’s of all the methods given in 5 interfaces.

  42. why do we need a Interface “OperationsFacade”in this pattern , whats the use of it . we could have just coded the “OperationsFacade” and made it a class. why do we first create a interface and then implement the interface?

  43. Very good article. The only part I kind of disagree with is the GoF’s definition: “Provide a unified interface to a set of interfaces in a subsystem”.

    I would have defined it as: “Provide a customized interface to a subset of features in a subsystem or subsytems”.

    In other words, the facade only provides an interface to what the application actually needs, and it hides both unused interfaces and the complexity of using the underlying subsystem features that are needed by the application.

  44. Very nice easy to visualize it, by giving real world example. Thanks Keep it up :)

  45. One of the best explanation i have read:)

    Thank!!! God bless you Sir!!!

  46. whats the difference between facade and a controler?

  47. Explained well bro :) can you plz post any Implementation ?? so that It will be much better one to understand.

  48. // Diff complex parts or diff subsystems
    // 1. CPU
    public class CPU {
    public void execute() {
    System.out.println(“CPU EXECUTE – Done”);
    }
    }

    // 2. Memory
    public class Memory {

    public void load() {
    System.out.println(“MEMORY LOAD – DONE”);
    }

    }

    // 3. Harddrive
    public class HardDrive {

    public void read() {
    System.out.println(“READ HardDrive – Done”);
    }

    }

    // Facade which provides an interface for all complex part to be accessed through one facade class

    // Facade
    public class ComputerFacade {

    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public ComputerFacade() {
    this.cpu = new CPU();
    this.memory = new Memory();
    this.hardDrive = new HardDrive();
    }

    public void startComputer() {
    cpu.execute();
    memory.load();
    hardDrive.read();
    System.out.println(“Computer Successfully Started!!!”) ;
    }
    }

    // Client class which calls only facade interface to access diff complex functionality

    public class Test_FacadePattern {

    public static void main(String[] args) {
    ComputerFacade facade = new ComputerFacade();
    facade.startComputer();
    }
    }

    =============================

    Thanks

  49. Hey good presentation. Could you please write on other patterns also?

  50. Juan Manuel Mauricio Zamarrón said on ,

    Hi, I have a question, if I have a complex subsystem, and I have only one client who needs only some operations, is factible that I can use the facade pattern?

  51. nice explaination…but where is the code????

  52. Could u please post some sample code with explanation

  53. Hi Joe

    Thanks for your nice articles on Design Patterns. I found it really helpful in understanding design patterns

    Thanks
    Senthil

  54. Nice article, explained so good and able to understand easily.

    keep it up the good work.

  55. Thanks…Can you also wrote about visitor design pattern..

  56. Thanks Joe. a doubt I have indeed. How come Facade and controller are different. The way i perceive controller is that, it is a class that juggles with several subsystems. If a client is directly calling Facade, may be in that case both are same?

  57. good article..ur articles r always good and simple to understand..keep it up

  58. Awesome article Joe, Keep up the good work

  59. I read some of the posts, you have explained in simple plain english with images and examples which is easier to understand. Keep it up this good work.

  60. superb explanation. Joe sir u have very good explanation power. It is the most important thing which few has it..

  61. Thanks nice one to understand well…

  62. Hi Joe,

    good broad explanation, but I think you pinched some areas without fully going through them.

    “In software scenario, you can have interfaces which acts as a facade. Methods in these interfaces contains the interaction sequence, formatting and converting data for input for components. As such it will not hold the business logic.”

    Ok so by your definition you don’t consider accessing DAO layer from the facades method (only using the already provided business service methods and formatting them in any way).

    Than you go to say
    “A controller is not a facade.”.
    In a way a controller does the same thing. It uses business services methods and formats/packages the model in the way the client needs it. On the other hand, (the only difference I see using this definition) the facade can be used by other systems, not just like in a controller fashion through http.

    In that sense it looks to me that a facade is another type of business service that can emerge from other business used in a common way by two or more clients (clients being either internal or external systems).

    You would do the same even if you need to use a DAO layer (not only formatting and converting data). Imagine you have BusinessService1 with method do1() and BusinessService2 with do2() and you see 2 (or more) clients using
    model1 = do1()
    model2 = do2()
    model3 = persistOrRetrieveUsingSomeDAO(model1, model2)

    You will feel the urge to refactor this and place it in one place, implicitly creating another business service.

    So to me it boils down to using the SRP + IOC/DI + extracting duplicated logic. This will lead to any of the scenarios above.

  63. Very well and properly and clearly explained.
    Thanks

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>