This is part of a series of posts demonstrating software design patterns using C# and .NET. The patterns are taken from the book Design Patterns by the Gang of Four. Here's the series index page.

What Is This Pattern?

The Facade pattern is a simple structure laid over a more complex structure.

(That's it. Yes, seriously. Facade is one of the simpler patterns.)

(You can move on to the next section now. Go on. Shoo!)

(Whaaat? You want more details? Fine.)

The idea is that if you don't want other code accessing the complex bits of a class or process, you hide those bits by covering them with a Facade.

(Hope you're happy now.)

The Rundown

  • Type: Structural
  • Useful? 5/5 (Extremely)
  • Good For: Hiding complexity which cannot be refactored away.
  • Example Code: On GitHub

The Participants

  • The Subsystems are any classes or objects which implement functionality but can be "wrapped" or "covered" by the Facade to simplify an interface.
  • The Facade is the layer of abstraction above the Subsystems, and knows which Subsystem to delegate appropriate work to.

A Delicious Example

To demonstrate how we use the Facade pattern, let's think about a restaurant.

In most kitchens, the work area is divided into sections. For this demo, we'll assume that our kitchen is divided into three areas: Hot Prep, where hot dishes like meats and pasta are made; Cold Prep, where cold dishes like salads and desserts are made; and the Bar, where drinks are prepared.

If you are a patron at this restaurant and you sit down at a booth, do you care what part of your meal is made at what section of the restaurant? Of course not. There is naturally a layer of abstraction in place: the server.

A female server works in a North Korean restaurant North Korea - Samjiyon waitress from Wikimedia, used under license

The server knows where to place each order and where to pick those parts of the order up from. We'll model this relationship to demonstrate how the Facade pattern can simplify the structure of our code.

First, let's create a class for the restaurant patron:

/// <summary>
/// Patron of the restaurant (duh!)
/// </summary>
class Patron  
{
    private string _name;

    public Patron(string name)
    {
        this._name = name;
    }

    public string Name
    {
        get { return _name; }
    }
}

Let's also define a base class representing all food items sold at this restaurant; an interface representing all sections of this restaurant's kitchen; and a class representing a patron's order:

/// <summary>
/// All items sold in the restaurant must inherit from this.
/// </summary>
class FoodItem { public int DishID; }

/// <summary>
/// Each section of the kitchen must implement this interface.
/// </summary>
interface KitchenSection  
{
    FoodItem PrepDish(int DishID);
}

/// <summary>
/// Orders placed by Patrons.
/// </summary>
class Order  
{
    public FoodItem Appetizer { get; set; }
    public FoodItem Entree { get; set; }
    public FoodItem Drink { get; set; }
}

Now we can start to model the sections of the kitchen, AKA the Subsystem participants. Here's the classes for ColdPrep, HotPrep, and Bar:

/// <summary>
/// A division of the kitchen.
/// </summary>
class ColdPrep : KitchenSection  
{
    public FoodItem PrepDish(int dishID)
    {
        //Go prep the cold item
        return new FoodItem()
        {
            DishID = dishID
        };
    }
}

/// <summary>
/// A division of the kitchen.
/// </summary>
class HotPrep : KitchenSection  
{
    public FoodItem PrepDish(int dishID)
    {
        //Go prep the hot entree
        return new FoodItem()
        {
            DishID = dishID
        };
    }
}

/// <summary>
/// A division of the kitchen.
/// </summary>
class Bar : KitchenSection  
{
    public FoodItem PrepDish(int dishID)
    {
        //Go mix the drink
        return new FoodItem()
        {
            DishID = dishID
        };
    }
}

Finally, we need the actual Facade participant, which is our Server class:

/// <summary>
/// The actual "Facade" class, which hides the complexity of the KitchenSection classes.
/// After all, there's no reason a patron should order each part of their meal individually.
/// </summary>
class Server  
{
    private ColdPrep _coldPrep = new ColdPrep();
    private Bar _bar = new Bar();
    private HotPrep _hotPrep = new HotPrep();

    public Order PlaceOrder(Patron patron, int coldAppID, int hotEntreeID, int drinkID)
    {
        Console.WriteLine("{0} places order for cold app #" + coldAppID.ToString()
                            + ", hot entree #" + hotEntreeID.ToString()
                            + ", and drink #" + drinkID.ToString() + ".");

        Order order = new Order();

        order.Appetizer = _coldPrep.PrepDish(coldAppID);
        order.Entree = _hotPrep.PrepDish(hotEntreeID);
        order.Drink = _bar.PrepDish(drinkID);

        return order;
    }
}

Will all of these in place, we can use the Main() to show how a patron might place an order and how the server (the Facade) would direct the appropriate pieces of that order to the kitchen sections (the Subsystems):

static void Main(string[] args)  
{
    Server server = new Server();

    Console.WriteLine("Hello!  I'll be your server today. What is your name?");
    var name = Console.ReadLine();

    Patron patron = new Patron(name);

    Console.WriteLine("Hello " + patron.Name + ". What appetizer would you like? (1-15):");
    var appID = int.Parse(Console.ReadLine());

    Console.WriteLine("That's a good one.  What entree would you like? (1-20):");
    var entreeID = int.Parse(Console.ReadLine());

    Console.WriteLine("A great choice!  Finally, what drink would you like? (1-60):");
    var drinkID = int.Parse(Console.ReadLine());

    Console.WriteLine("I'll get that order in right away.");

    server.PlaceOrder(patron, appID, entreeID, drinkID);  //Here's what the Facade simplifies

    Console.ReadKey();
}

If we run the sample app, an output might look like this:

A demo run of the Facade pattern's sample application, showing the patron's selections.

Will I Ever Need This Pattern?

All the damn time. Seriously, the Facade pattern is so general that it applies to almost every major app I've worked on, especially those where I couldn't refactor or modify pieces of said apps for various reasons.

Summary

The Facade pattern is a simple (or at least simpler) overlay on top of a group of more complex subsystems. The Facade knows which Subsystem to direct different kinds of work toward. And it is really, really common, so it's one of the patterns we should know thoroughly.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.

Happy Coding!

(That's the end of the post. Yes, seriously. No I'm not writing another one right this second, you'll just have to wait until tomorrow. So there.)

Get My eBook FREE!

Did you enjoy this post? This article and 21 others are also in my free eBook, "The Daily Design Pattern", which you can get just by signing up for my email list.