Click here to Skip to main content
15,875,646 members
Articles / Programming Languages / C#
Article

Understanding and Implementing Facade Pattern in C#

Rate me:
Please Sign up or sign in to vote.
4.89/5 (39 votes)
21 Oct 2012CPOL4 min read 127.5K   1.1K   51   17
This article talks about the facade pattern. When is this pattern useful. This article also presents a rudimentary approach to implement the facade pattern.

Introduction

This article talks about the facade pattern. When is this pattern useful. This article also presents a rudimentary approach to implement the facade pattern.

Background 

There are some scenarios in our application, we need to work with a series of objects to perform certain task. For example, If we are writing software for a universal remote and I want to turn off all the devices then I have few options. First I can manually select each device and turn them off one by one. This was rather a crude approach so why not automate this inside the remote itself. So I can have a button that will turn off all the devices. Now to turn off all the devices all I need to so is to push this button. The button press command of this remote will now talk to all the device controllers and turn them off.

Now if I need the similar functionality to be executed automatically at 12 o'clock in night. Now this timer based event will also talk to all the devices and stop them all. So the problem here is that in all the scenarios I need to have this functionality I need to talk to these objects.

There is one more approach in designing this solution. Why not have an object whose responsibility is to stop all the devices. Now whenever I need to stop all the devices, I need to call this object only. This is exactly the philosophy behind the facade pattern. GoF defines facade pattern as "Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use."

To visualize this pattern:

Image 1

The important thing to note here is that the facade object is simply providing the set of functionalities in an easier way. It is not altering the interface of the subsystem. The subsystem classes can still be accessed by the other parts of the system. The facade will provide the group of functionalities in a single location.

Using the code

To illustrate the facade pattern, Lets try to look into a small example. Lets try to implement a hypothetical facade object to work with some Windows Phone controller objects. First let me define the problem.

Every morning when I go for jogging, I have to make the following changes in my Windows phone device:

  1. Turn off the wifi
  2. Switch on the Mobile Data
  3. Turn on the GPS
  4. Turn on the Music
  5. Start the Sports-Tracker

And after coming back from jogging, follwing needs to be done from my part:

  1. Share Sports tracker stats on twitter and facebook
  2. Stop the Sports Tracker
  3. Turn off the Music
  4. Turn off the GPS
  5. Turn off the Mobile Data
  6. Turn on the wifi

All this is being done manually right now. So to simulate the behavior lets first implement the subsystem i.e. the dummy controller classes.

C#
class GPSController
{
    bool isSwitchedOn = false;

    public bool IsSwitchedOn
    {
        get
        {
            return isSwitchedOn;
        }
        set
        {
            isSwitchedOn = value;
            DisplayStatus();
        }
    }

    private void DisplayStatus()
    {
        string status = (isSwitchedOn == true) ? "ON" : "OFF";
        Console.WriteLine("GPS Switched {0}", status);
    }
}

Other controllers like MobileDataController, MusicController, WifiController are also implemented in a similar way.

Now to emulate the App behavior. 

C#
class SportsTrackerApp
{
    public void Start()
    {
        Console.WriteLine("Sports Tracker App STARTED");
    }

    public void Stop()
    {
        Console.WriteLine("Sports Tracker App STOPPED");
    }

    public void Share()
    {
        Console.WriteLine("Sports Tracker: Stats shared on twitter and facebook.");
    }
}

So right now with What I am doing is changing all the settings manually and then starting the App manually. Which can be visualized in form of code as:

C#
static void Main(string[] args)
{
    // The phone has been booted up and all the controllers are running
    GPSController gps = new GPSController();
    MobileDataController data = new MobileDataController();
    MusicController zune = new MusicController();
    WifiController wifi = new WifiController();

    ///////////// Going for Jogging /////////////////////

    // 1. Turn off the wifi
    wifi.IsSwitchedOn = false;

    // 2. Switch on the Mobile Data
    data.IsSwitchedOn = true;

    // 3. Turn on the GPS
    gps.IsSwitchedOn = true;

    // 4. Turn on the Music
    zune.IsSwitchedOn = true;

    // 5. Start the Sports-Tracker
    SportsTrackerApp app = new SportsTrackerApp();
    app.Start();

    ///////////// Back from Jogging /////////////////////
    Console.WriteLine();

    // 0. Share Sports tracker stats on twitter and facebook
    app.Share();

    // 1. Stop the Sports Tracker
    app.Stop();

    // 2. Turn off the Music
    zune.IsSwitchedOn = false;

    // 3. Turn off the GPS
    gps.IsSwitchedOn = false;

    // 4. Turn off the Mobile Data
    data.IsSwitchedOn = false;

    // 5. Turn on the wifi
    wifi.IsSwitchedOn = true;          
}

Note: All this is to emulate the behavior of my Windows Phone. If we run this application the output will be:

Image 2

Now I have to write myself a facade application that will do all this for me internally. I will write an class that will simply expose two methods like StartJogging and StopJogging to me. internally it will take care of doing all these activities. So let me write a facade now: 

C#
class MyJoggingFacade
{
    // These handles will be passed to this facade in a real application
    // also on actual device these controllers will be singleton too.
    GPSController gps = new GPSController();
    MobileDataController data = new MobileDataController();
    MusicController zune = new MusicController();
    WifiController wifi = new WifiController();
    
    SportsTrackerApp app = null;
        
    public void StartJogging()
    {
        // 1. Turn off the wifi
        wifi.IsSwitchedOn = false;

        // 2. Switch on the Mobile Data
        data.IsSwitchedOn = true;

        // 3. Turn on the GPS
        gps.IsSwitchedOn = true;

        // 4. Turn on the Music
        zune.IsSwitchedOn = true;

        // 5. Start the Sports-Tracker
        app = new SportsTrackerApp();
        app.Start();
    }

    public void StopJogging()
    {
        // 0. Share Sports tracker stats on twitter and facebook
        app.Share();

        // 1. Stop the Sports Tracker
        app.Stop();

        // 2. Turn off the Music
        zune.IsSwitchedOn = false;

        // 3. Turn off the GPS
        gps.IsSwitchedOn = false;

        // 4. Turn off the Mobile Data
        data.IsSwitchedOn = false;

        // 5. Turn on the wifi
        wifi.IsSwitchedOn = true;
    }
}

Now the same functionality could be achieved by doing a minimal amount of manual work from the user.

C#
static void Main(string[] args)
{
    MyJoggingFacade facade = new MyJoggingFacade();

    facade.StartJogging();
    Console.WriteLine();
    facade.StopJogging();          
}
Image 3

Before summing up let us compare the class diagram of this implementation with the facade pattern:

Image 4

Note: The sample application talks about Apps and controllers. The real world implementation of these must be in form of separate application. We have considered all of them as classes of single application just for illustrating the facade pattern. If we actually implement such an application that will also be a facade but it will be a facade application rather than implementation of facade pattern.

Point of interest

In this article we have discussed about facade pattern. Often this pattern is confused with adapter pattern but in fact adapter pattern actually presents an altered interface of a system to the client and the original interface is not accessible. The facade pattern on the other hand provides a simpler interface of the subsystem. The original objects/system can still be accessed. I hope this has been informative.

History

  • 22 October 2012: First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
PraiseNice article Pin
kata.yaswanth31-Jul-16 19:19
kata.yaswanth31-Jul-16 19:19 
QuestionNice article. Pin
Bhushan Deshmukh26-Jun-16 7:12
Bhushan Deshmukh26-Jun-16 7:12 
PraiseGreat explanation Pin
subhadeep.a.mitra29-Dec-15 7:41
subhadeep.a.mitra29-Dec-15 7:41 
QuestionCrystal clear Pin
Arjsrya20-Jul-15 17:24
professionalArjsrya20-Jul-15 17:24 
QuestionMy vote of 5 Pin
GenadyT23-Mar-14 4:14
professionalGenadyT23-Mar-14 4:14 
GeneralFatanstic explanation Pin
Rasik Bihari Tiwari13-Feb-14 1:20
professionalRasik Bihari Tiwari13-Feb-14 1:20 
QuestionIf subclasses are added Pin
Member 1024059129-Aug-13 5:09
Member 1024059129-Aug-13 5:09 
QuestionCan you make facades static? Pin
duncanwilde4524-Aug-13 23:42
duncanwilde4524-Aug-13 23:42 
GeneralMy vote of 5 Pin
cpsglauco23-Jul-13 8:37
cpsglauco23-Jul-13 8:37 
GeneralMy vote of 5 Pin
codesri16-Jul-13 3:29
codesri16-Jul-13 3:29 
QuestionMy Vote of 5 Pin
Vasanthjai3-Jul-13 19:49
Vasanthjai3-Jul-13 19:49 
GeneralMy vote of 5 Pin
paul_cheung16-Jun-13 16:08
paul_cheung16-Jun-13 16:08 
GeneralMy vote of 5 Pin
Bill Do15-Apr-13 18:05
Bill Do15-Apr-13 18:05 
GeneralMy vote of 5 Pin
ojanacek20-Mar-13 9:57
ojanacek20-Mar-13 9:57 
GeneralNice and Clean Article Pin
prakash_2108-Mar-13 15:42
prakash_2108-Mar-13 15:42 
GeneralMy vote of 5 Pin
prakash_2108-Mar-13 15:38
prakash_2108-Mar-13 15:38 
QuestionGreat article - thanks Pin
Petr Kohout21-Oct-12 23:06
Petr Kohout21-Oct-12 23:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.