Facade Design Pattern

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 added on 29/01/2012.

«

»

Comments on "Facade Design Pattern"

  1. kp says:

    very good article….keep it up…Excellent work

  2. Krishna says:

    Very well and properly and clearly explained.
    Thanks

  3. Despot says:

    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.

  4. abhimanyu says:

    Thanks nice one to understand well…

  5. Sankar says:

    Great Explain

  6. Anonymous says:

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

  7. kishore says:

    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.

  8. Aishvarya says:

    Awesome article Joe, Keep up the good work

  9. abhijeet says:

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

  10. Manoj kataria says:

    Good one !!

  11. Omar says:

    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?

  12. manu says:

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

  13. Shanmugam says:

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

    keep it up the good work.

  14. Gopi says:

    Very nice article

  15. SenthilRajan says:

    Hi Joe

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

    Thanks
    Senthil

  16. Anonymous says:

    Could u please post some sample code with explanation

  17. Anonymous says:

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

  18. Emad Aghayi says:

    Excellent.

    Keep it going …

  19. Emad Aghayi says:

    Excellent,
    Keep it going…

  20. Dilip says:

    Good one

  21. Subhajit says:

    Good one … Thanks :)

  22. is Facade is reverse to the Adapter ?

  23. Juan Manuel Mauricio Zamarrón says:

    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?

  24. Deepak says:

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

  25. Manikumari Kancharla says:

    Thanks Jay

  26. Priyanka says:

    Thanks a Million. Its helpful.

  27. Jay says:

    // 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

  28. Jay says:

    Thanks!!!

  29. Karthik says:

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

  30. Kirtan says:

    thanks…

  31. Qadeer Hussain says:

    whats the difference between facade and a controler?

  32. Bhasker Tiwari says:

    One of the best explanation i have read:)

    Thank!!! God bless you Sir!!!

  33. cherry says:

    great depiction……

  34. Said Naeem Shah says:

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

  35. deepak says:

    nice tutorial.

  36. TomH says:

    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.

  37. avinash says:

    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?

  38. Kiran says:

    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.

  39. manoj says:

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

  40. Anonymous says:

    Nice article ……

  41. mall.rajeshmall@gmail.com says:

    very nice

  42. Manoswitha says:

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

  43. SandyaReddy says:

    Good Example, Good Job

  44. Preethi says:

    Very clear Article for Beginner.

  45. Sameer says:

    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

  46. divya says:

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

    • Lokesh says:

      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.

      • JavaEnthusiast says:

        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)

  47. Subha says:

    Simple example and clear…Keep sharing :)

  48. Anonymous says:

    can we say this facade as a front controller?

  49. rohit says:

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

  50. SK says:

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

  51. Anonymous says:

    Nice article

  52. Saggy says:

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

  53. Anonymous says:

    Nice Explaination :)

  54. Anonymous says:

    Excellent work….

  55. Anandhan says:

    Bullet points :-)

  56. Gurudas says:

    It will be great help if code also provided

  57. Amol says:

    Nice example !

  58. Rameshwar says:

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

  59. D.thirupathi says:

    wonderful explanation and nice example

  60. Srinivas says:

    its very neatly explained!!!!

  61. rameez says:

    excellent article

  62. Sarath says:

    It’s really good explaining with examples

  63. Sezin Karli says:

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

  64. Nithiya says:

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

  65. king says:

    Please provide me some simplejava code example.

  66. Sanjukta says:

    Please provide some java code example.

  67. Anonymous says:

    Its very good artical.

  68. Anonymous says:

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

    • Despot says:

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

  69. Anonymous says:

    Thanks for the explination

    r@j

  70. Subrat says:

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

  71. Anonymous says:

    Alles klar

  72. Anonymous says:

    Joe,

    Good Job !!

    Adesh

  73. John Sambath says:

    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();
    }
    }

    • Lokesh says:

      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.

  74. Anonymous says:

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

  75. pankaj says:

    good article!!

  76. Rajesh says:

    liked it!!

  77. Mahsa says:

    Nice examples and guidance to avoid mistakes!

  78. Tribhuwan says:

    Good explanation with example. Thank You for your blogs.

  79. Raj says:

    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

  80. Prafulla says:

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

  81. Anonymous says:

    very helpful, thanks a lot !

  82. Anonymous says:

    Excellent. Very clear

  83. Anonymous says:

    excellent job done

  84. prasanti says:

    clear explanation

  85. Rodolfo Guzman says:

    Very nice and well explained! Thanks!

  86. Abir says:

    Excellent. Very clear concept

  87. Naveen says:

    Excellent!!

    Simple and relevant information.

  88. sivakumar says:

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

  89. prity says:

    nice article

  90. trim says:

    nice examples giving clear roadmap of design pattern

  91. Ranjit says:

    Very good Article
    Keep it going :)

  92. Anonymous says:

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

  93. santosh says:

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

  94. Sidharth says:

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

  95. indrajeet says:

    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??

  96. indrajeet says:

    nice artical… :)

  97. Joe says:

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

    I will try to add some code example soon.

  98. Manoj Dwivedi says:

    greate example and keypoints

  99. Anonymous says:

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

  100. Suyog says:

    excellent!!

  101. Anonymous says:

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

  102. cndhu says:

    Please explain coupling and cohesion

  103. Dhiren says:

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

  104. Anonymous says:

    nice article sir….

  105. Chaitanya says:

    Very good article… Keep going …

  106. Itudoben says:

    Good article.

  107. Sudheer says:

    Very Good Article

  108. Suman says:

    How is it different from factory?

  109. Ahmad says:

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

  110. Rajesh says:

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

    Keep growing..

  111. Kat says:

    Clear :)

  112. Alex says:

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

Comments are closed.