kevin
kevin

Reputation: 14095

What is the Facade design pattern?

Is Facade a class which contains a lot of other classes?

What makes it a design pattern? To me, it is like a normal class.

Can you explain to me this Facade pattern?

Upvotes: 204

Views: 134246

Answers (20)

Ravindra babu
Ravindra babu

Reputation: 38950

Regarding your queries:

Is Facade a class which contains a lot of other classes?

Yes. It is a wrapper for many sub-systems in application.

What makes it a design pattern? For me, it is like a normal class

All design patterns too are normal classes. @Unmesh Kondolikar rightly answered this query.

Can you explain me about this Facade, I am new to design patterns.

According to GoF, Facade design pattern is defind as :

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

The Facade pattern is typically used when:

  1. A simple interface is required to access a complex system.
  2. Need an entry point to each level of layered software.

Let's take a real word example of cleartrip website.

This website provides options to book

  1. Flights
  2. Hotels
  3. Flights + Hotels

Code snippet:

import java.util.*;

public class TravelFacade{
    FlightBooking flightBooking;
    TrainBooking trainBooking;
    HotelBooking hotelBooking;

    enum BookingType {
        Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
    }; 
    
    public TravelFacade(){
        flightBooking = new FlightBooking();
        trainBooking = new TrainBooking();
        hotelBooking = new HotelBooking();        
    }
    public void book(BookingType type, BookingInfo info){
        switch(type){
            case Flight:
                // book flight;
                flightBooking.bookFlight(info);
                return;
            case Hotel:
                // book hotel;
                hotelBooking.bookHotel(info);
                return;
            case Train:
                // book Train;
                trainBooking.bookTrain(info);
                return;
            case Flight_And_Hotel:
                // book Flight and Hotel
                flightBooking.bookFlight(info);
                hotelBooking.bookHotel(info);
                return;
             case Train_And_Hotel:
                // book Train and Hotel
                trainBooking.bookTrain(info);
                hotelBooking.bookHotel(info);
                return;                
        }
    }
}
class BookingInfo{
    String source;
    String destination;
    Date    fromDate;
    Date     toDate;
    List<PersonInfo> list;
}
class PersonInfo{
    String name;
    int       age;
    Address address;
}
class Address{

}
class FlightBooking{
    public FlightBooking(){
    
    }
    public void bookFlight(BookingInfo info){
    
    }
}
class HotelBooking{
    public HotelBooking(){
    
    }
    public void bookHotel(BookingInfo info){
    
    }
}
class TrainBooking{
    public TrainBooking(){
    
    }
    public void bookTrain(BookingInfo info){
    
    }
}

Explanation:

  1. FlightBooking, TrainBooking and HotelBooking are different sub-systems of large system : TravelFacade

  2. TravelFacade offers a simple interface to book one of below options

     Flight Booking
     Train Booking 
     Hotel Booking
     Flight + Hotel booking 
     Train + Hotel booking
    
  3. book API from TravelFacade internally calls below APIs of sub-systems

     flightBooking.bookFlight
     trainBooking.bookTrain(info);
     hotelBooking.bookHotel(info);
    
  4. In this way, TravelFacade provides simpler and easier API with-out exposing sub-system APIs.

Upvotes: 10

Michu93
Michu93

Reputation: 5743

I like an example from Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates - Head First Design Patterns book. Example: let's assume you created home theatre and finally you would like to watch a movie. So you have to do:

        Amplifier amplifier = new Amplifier();
        CdPlayer cdPlayer = new CdPlayer();
        DvdPlayer dvdPlayer = new DvdPlayer();
        Lights lights = new Lights();
        PopcornPopper popcornPopper = new PopcornPopper();
        Projector projector = new Projector();
        Screen screen = new Screen();

        popcornPopper.turnOn();
        popcornPopper.pop();
        amplifier.turnOn();
        amplifier.setVolume(10);
        lights.turnOn();
        lights.dim(10);
        screen.up();
        dvdPlayer.turnOn();
        dvdPlayer.play();

what happens when movie is over? You have to do the same but in reverse order so complexity of watch and end movie is becoming very complex. Facade pattern says that you can create a facade and let user just call one method instead of calling all of this. Let's create facade:

public class HomeTheatherFacade {
    Amplifier amplifier;
    DvdPlayer dvdPlayer;
    CdPlayer cdPlayer;
    Projector projector;
    Lights lights;
    Screen screen;
    PopcornPopper popcornPopper;

    public HomeTheatherFacade(Amplifier amplifier, DvdPlayer dvdPlayer, CdPlayer cdPlayer, Projector projector, Lights lights, Screen screen, PopcornPopper popcornPopper) {
    this.amplifier = amplifier;
    this.dvdPlayer = dvdPlayer;
    this.cdPlayer = cdPlayer;
    this.projector = projector;
    this.lights = lights;
    this.screen = screen;
    this.popcornPopper = popcornPopper;
}

public void watchMovie(String movieTitle) {
    popcornPopper.turnOn();
    popcornPopper.pop();
    amplifier.turnOn();
    amplifier.setVolume(10);
    lights.turnOn();
    lights.dim(10);
    screen.up();
    dvdPlayer.turnOn();
    dvdPlayer.play();
}

public void endMovie() {
    dvdPlayer.turnOff();
    screen.down();
    lights.turnOff();
    amplifier.turnOff();
}
}

and now instead of calling all of this you can just call watchMovie and endMovie methods:

public class HomeTheatherFacadeTest {
    public static void main(String[] args){
        Amplifier amplifier = new Amplifier();
        CdPlayer cdPlayer = new CdPlayer();
        DvdPlayer dvdPlayer = new DvdPlayer();
        Lights lights = new Lights();
        PopcornPopper popcornPopper = new PopcornPopper();
        Projector projector = new Projector();
        Screen screen = new Screen();
        
        HomeTheatherFacade homeTheatherFacade = new HomeTheatherFacade(amplifier, dvdPlayer, cdPlayer, projector, lights, screen, popcornPopper);
        homeTheatherFacade.watchMovie("Home Alone");
        homeTheatherFacade.endMovie();
    }
}

So:

"The Facade Pattern provides a unified interface to a set of interfaces in a subsytem. Facade defines a higher level interface that makes the subsystem easier to use."

Upvotes: 2

Jeff Schreib
Jeff Schreib

Reputation: 31

Its simply creating a wrapper to call multiple methods . You have an A class with method x() and y() and B class with method k() and z(). You want to call x, y, z at once , to do that using Facade pattern you just create a Facade class and create a method lets say xyz(). Instead of calling each method (x,y and z) individually you just call the wrapper method (xyz()) of the facade class which calls those methods .

Similar pattern is repository but it s mainly for the data access layer.

Upvotes: 3

user6102894
user6102894

Reputation:

Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. 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.

Source: https://sourcemaking.com/design_patterns/facade

Upvotes: 4

Jordan Enev
Jordan Enev

Reputation: 18684

There is a very good real-life example of the pattern  - The car starter engine.

As drivers, we just turn the key on and the car get started. As simple as possible. Behind the scenes, many other car systems are involved (as battery, engine, fuel, etc.), in order the car to start successfully, but they are hidden behind the starter.

As you can see, the car starter is the Facade. It gives us easy to use interface, without worrying about the complexity of all other car systems.

Let's summarize:

The Facade pattern simplifies and hides the complexity of large code blocks or APIs, providing a cleaner, understandable and easy of use interface.

Upvotes: 6

Arun Raaj
Arun Raaj

Reputation: 1798

A short and simple explanation:

  • Facade pattern provides a unified interface to a set of interface(s) in a subsystem.
  • Facade defines a higher-level interface that makes the subsystem easier to use.

Try to understand the scenario with and without Façade:
If you want to transfer the money from accout1 to account2 then the two subsystems to be invoked are, withdraw from account1 and deposit to account2.

with and without facade

Upvotes: 23

user1694660
user1694660

Reputation: 141

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

Upvotes: 1

KaviK
KaviK

Reputation: 625

Facade hides the complexities of the system and provides an interface to the client from where the client can access the system.

public class Inventory {
public String checkInventory(String OrderId) {
    return "Inventory checked";
}
}

public class Payment {
public String deductPayment(String orderID) {
    return "Payment deducted successfully";
}
}


public class OrderFacade {
private Payment pymt = new Payment();
private Inventory inventry = new Inventory();

public void placeOrder(String orderId) {
    String step1 = inventry.checkInventory(orderId);
    String step2 = pymt.deductPayment(orderId);
    System.out
            .println("Following steps completed:" + step1
                    + " & " + step2);
   }
}

public class Client {
       public static void main(String args[]){
         OrderFacade orderFacade = new OrderFacade();
         orderFacade.placeOrder("OR123456");
         System.out.println("Order processing completed");
       }
  }

Upvotes: 31

Aravind
Aravind

Reputation: 4173

As explained in the previous answer it provides a simple interface to the consuming client. For example: "watch ESPN" is the intended function. But it involves several steps like:

  1. Switch on TV if required;
  2. Check for satellite/cable functioning;
  3. Switch to ESPN if required.

But the facade will simplify this and just provide "watch ESPN" function to the client.

Upvotes: 45

Program-Me-Rev
Program-Me-Rev

Reputation: 6634

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

The Facade design pattern is a structural pattern as it defines a manner for creating relationships between classes or entities. The facade design pattern is used to define a simplified interface to a more complex subsystem.

The facade pattern is ideal when working with a large number of interdependent classes, or with classes that require the use of multiple methods, particularly when they are complicated to use or difficult to understand. The facade class is a "wrapper" that contains a set of members that are easily understood and simple to use. These members access the subsystem on behalf of the facade user, hiding the implementation details.

The facade design pattern is particularly useful when wrapping subsystems that are poorly designed but cannot be refactored because the source code is unavailable or the existing interface is widely used. Sometimes you may decide to implement more than one facade to provide subsets of functionality for different purposes.

One example use of the facade pattern is for integrating a web site with a business application. The existing software may include large amounts of business logic that must be accessed in a particular manner. The web site may require only limited access to this business logic. For example, the web site may need to show whether an item for sale has reached a limited level of stock. The IsLowStock method of the facade class could return a Boolean value to indicate this. Behind the scenes, this method could be hiding the complexities of processing the current physical stock, incoming stock, allocated items and the low stock level for each item.

Upvotes: 3

Erdem Gezer
Erdem Gezer

Reputation: 3272

Wikipedia has a great example of Facade pattern.

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

Upvotes: 106

Saurabh
Saurabh

Reputation: 7843

It is basically single window clearance system.You assign any work it will delegate to particular method in another class.

Upvotes: 1

Sai Sunder
Sai Sunder

Reputation: 1021

All design patterns are some classes arranged in some way or other that suits a specific application. The purpose of facade pattern is to hide the complexity of an operation or operations. You can see an example and learn facade pattern from http://preciselyconcise.com/design_patterns/facade.php

Upvotes: 2

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

A design pattern is a common way of solving a recurring problem. Classes in all design patterns are just normal classes. What is important is how they are structured and how they work together to solve a given problem in the best possible way.

The Facade design pattern simplifies the interface to a complex system; because it is usually composed of all the classes which make up the subsystems of the complex system.

A Facade shields the user from the complex details of the system and provides them with a simplified view of it which is easy to use. It also decouples the code that uses the system from the details of the subsystems, making it easier to modify the system later.

http://www.dofactory.com/Patterns/PatternFacade.aspx

http://www.blackwasp.co.uk/Facade.aspx

Also, what is important while learning design patterns is to be able to recognize which pattern fits your given problem and then using it appropriately. It is a very common thing to misuse a pattern or trying to fit it to some problem just because you know it. Be aware of those pitfalls while learning\using design patterns.

Upvotes: 200

ManojPatra
ManojPatra

Reputation: 114

A facade exposes simplified functions that are mostly called and the implementation conceals the complexity that clients would otherwise have to deal with. In general the implementation uses multiple packages, classes and function there in. Well written facades make direct access of other classes rare. For example when I visit an ATM and withdraw some amount. The ATM hides whether it is going straight to the owned bank or is it going over a negotiated network for an external bank. The ATM acts like a facade consuming multiple devices and sub-systems that as a client I do not have to directly deal with.

Upvotes: 5

aish
aish

Reputation: 3019

Another example of facade: say your application connects to database and display results on the UI. You can use facade to make your application configurable, as in run using database or with mock objects. So you will make all the database calls to the facade class, where it will read app config and decide to fire the db query or return the mock object. this way application becomes db independent in case db is unavailable.

Upvotes: 5

Anand Patel
Anand Patel

Reputation: 6431

One additional use of Façade pattern could be to reduce the learning curve of your team. Let me give you an example:

Let us assume that your application needs to interact with MS Excel by making use of the COM object model provided by the Excel. One of your team members knows all the Excel APIs and he creates a Facade on top of it, which fulfills all the basic scenarios of the application. No other member on the team need to spend time on learning Excel API. The team can use the facade without knowing the internals or all the MS Excel objects involved in fulfilling a scenario. Is not it great?

Thus, it provides a simplified and unified interface on top of a complex sub-system.

Upvotes: 6

Aim Kai
Aim Kai

Reputation: 2919

The facade pattern is a wrapper of many other interfaces in a result to produce a simpler interface.

Design patterns are useful as they solve recurring problems and in general simplify code. In a team of developers who agree to use the same patterns it improves efficiency and understanding when maintaining each others code.

Try reading about more patterns:

Facade Pattern: http://www.dofactory.com/Patterns/PatternFacade.aspx#_self1

or more generally: http://www.dofactory.com/Patterns/Patterns.aspx

Upvotes: 6

Sean Hunter
Sean Hunter

Reputation: 1051

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Upvotes: 4

llMll
llMll

Reputation: 505

A facade should not be described as a class which contains a lot of other classes. It is in fact a interface to this classes and should make the usage of the classes easier otherwise the facade class is useless.

Upvotes: 11

Related Questions