C# Corner

The Facade Pattern in .NET

Eric Vogel covers shows how to use the Facade pattern to create a simple unified interface for a collection of interfaces in a .NET application.

The Facade pattern is a common software design pattern used to create a simple unified interface for a set of interfaces in a system. The Facade interface is a higher-level interface that allows easier control of a set of subsystem interfaces without affecting the subsystem interfaces. Today I'll demonstrate how to implement the Facade pattern in the .NET Framework.

The test scenario is a set of vehicle sub controllers, which include an engine controller, traction control controller, transmission controller, and a tachometer controller. Each of these subsystems have their own API. To create a vehicle would require creating each of these controllers and making sure each controller is used appropriately to create a functioning system. To simply this API, I'll use the Facade pattern to create one Facade class -- VehicleFacade -- that's responsible for creation and orchestration of each vehicle subsystem. In this way, the end user only has to know the details of the Facade interface.

I start by creating a new C# console application, then a Controllers directory in the project. First I add the IEngineController, which defines the contract for an engine:

namespace VSMFacadePattern.Controllers
{
    public interface IEngineController
    {
        bool Running { get; }
        void Start();
        void Stop();
    }
}

Next I implement the EngineController class that implements the IEngineController interface, as seen in Listing 1.

using System;

namespace VSMFacadePattern.Controllers
{
    public class EngineController : IEngineController
    {
        public bool Running { get; private set; }

        public void Start()
        {
            Running = true;
            Console.WriteLine("Engine started");
        }

        public void Stop()
        {
            Running = false;
            Console.WriteLine("Engine stopped");
        }
    }
}

Listing 1: EngineController.cs

Next I define the ITachometerController interface that defines the responsibilities of a tachometer:

namespace VSMFacadePattern.Controllers
{
    public interface ITachometerController
    {
        int Rpm { get; set; }
        int Limit { get; }
    }
}

Then I add the TachometerController that implements the ITachometerController interface:

namespace VSMFacadePattern.Controllers
{
    public class TachometerController : ITachometerController
    {
        public int Rpm { get; set; }
        public int Limit { get; private set; }

        public TachometerController()
        {
            Limit = 5000;
        }
    }
}

Next I define the ITransmissionController interface that defines the contract for a transmission:

namespace VSMFacadePattern.Controllers
{
    public interface ITransmissionController
    {
        int Gear { get; set; }
        int MaxGear { get; set; }
        void ShiftUp();
        void ShiftDown();
    }
}

Then I implement the ITransmissionController interface via the TramissionController class, as seen in Listing 2.

using System;

namespace VSMFacadePattern.Controllers
{
    public class TransmissionController : ITransmissionController
    {
        public int Gear { get; set; }
        public int MaxGear { get; set; }

        public void ShiftUp()
        {
            if (Gear < MaxGear)
            {
                Gear++;
                Console.WriteLine(string.Format("Shifted up to gear {0}", Gear));
            }
        }

        public void ShiftDown()
        {
            if (Gear > 0)
            {
                Gear--;
                Console.WriteLine(string.Format("Shifted down to gear {0}", Gear));
            }
        }
    }
}

Listing 2: TransmissionController.cs

Next I add the ITractionController interface that defines the responsibilities of a traction control:

namespace VSMFacadePattern.Controllers
{
    public interface ITractionControlController
    {
        bool Enabled { get; set; }
        void Enable();
        void Disable();
    }
}

Then I implement the ITractionController interface via the TractionController interface, as seen in Listing 3.

using System;

namespace VSMFacadePattern.Controllers
{
    public class TractionControlController : ITractionControlController
    {
        public bool Enabled { get; set; }

        public void Enable()
        {
            Enabled = true;
            Console.WriteLine("Traction controled enabled");
        }

        public void Disable()
        {
            Enabled = false;
            Console.WriteLine("Traction control disabled");
        }
    }
}

Listing 3: TractionControlController.cs

Now it's time to define the Facade pattern interface that will simply the orchestration of the vehicle controller subsystem interfaces. This interface is simply called the IVehicleFacade interface:

namespace VSMFacadePattern
{
    public interface IVehicleFacade
    {
        void Start();
        void Accelerate();
        void Brake();
        void Off();
    }
}

Now it's time to implement the VehicleFacade class, which implements the IVehicleFacade interface. First I add a using state for the Controllers namespace:

using VSMFacadePattern.Controllers;

Next, I add read-only properties for each of the vehicle subsystems:

 private readonly IEngineController _engineController;
 private readonly ITransmissionController _transmissionController;
 private readonly ITractionControlController _tractionControlController;
 private readonly ITachometerController _tachometerController;

The constructor assigns each of the vehicle subsystems from the given concrete controllers:

public VehicleFacade(IEngineController engineController, ITransmissionController transmissionController,
    ITractionControlController tractionControlController, ITachometerController tachometerController)
{
    _engineController = engineController;
    _transmissionController = transmissionController;
    _tractionControlController = tractionControlController;
    _tachometerController = tachometerController;
}

The constructor is defined in this way to allow for easy integration with an inversion of control framework, which would allow for theĀ  subsystem interfaces to map to concrete classes at application startup or runtime.

Next I implement the Start() method that simply starts the engine and enables the traction control system:

public void Start()
{
    _engineController.Start();
    _tractionControlController.Enable();
}

Then I implement the Accelerate method, which updates the tachometer and shifts up the gear if it's at rest or above the tachometer's shift limit:

public void Accelerate()
{
    _tachometerController.Rpm += 500;
    if (_tachometerController.Rpm >= _tachometerController.Limit || _transmissionController.Gear == 0)
    {
        _transmissionController.ShiftUp();
    }
}

Next I implement the Brake() method, which updates the tachometer and shifts down the gear if the RPM reading is at or below a set limit:

{
    _tachometerController.Rpm -= 500;
    if (_tachometerController.Rpm <= 1500)
        _transmissionController.ShiftDown();
}

Last, I implement the Off() method that disables the traction control system and stops the engine:

public void Off()
{
    _tractionControlController.Disable();
    _engineController.Stop();
}

See Listing 4 for the completed VehicleFacade class implementation.

using VSMFacadePattern.Controllers;

namespace VSMFacadePattern
{
    public class VehicleFacade : IVehicleFacade
    {
        private readonly IEngineController _engineController;
        private readonly ITransmissionController _transmissionController;
        private readonly ITractionControlController _tractionControlController;
        private readonly ITachometerController _tachometerController;

        public VehicleFacade(IEngineController engineController, ITransmissionController transmissionController,
            ITractionControlController tractionControlController, ITachometerController tachometerController)
        {
            _engineController = engineController;
            _transmissionController = transmissionController;
            _tractionControlController = tractionControlController;
            _tachometerController = tachometerController;
        }

        public void Start()
        {
            _engineController.Start();
            _tractionControlController.Enable();
        }

        public void Accelerate()
        {
            _tachometerController.Rpm += 500;
            if (_tachometerController.Rpm >= _tachometerController.Limit || _transmissionController.Gear == 0)
            {
                _transmissionController.ShiftUp();
            }
        }

        public void Brake()
        {
            _tachometerController.Rpm -= 500;
            if (_tachometerController.Rpm <= 1500)
                _transmissionController.ShiftDown();
        }

        public void Off()
        {
            Break();
            _tractionControlController.Disable();
            _engineController.Stop();
        }
    }
}

Listing 4: VehicleFacade.cs

Now it's time to create the vehicle test driver. I open up the Program class file and add a using statement for my Controllers namespace:

using VSMFacadePattern.Controllers;

The first step is to create a new VehicleFacade instance:

VehicleFacade vehicle = new VehicleFacade(new EngineController(), new TransmissionController(),
                new TractionControlController(), new TachometerController());

Then start the vehicle:

vehicle.Start();

Then accelerate the vehicle from gear rest up to gear six:

for (int i = 0; i < 20; i++)
{
    System.Threading.Thread.Sleep(100);
    vehicle.Accelerate();
}

Then apply the brakes until the vehicle is at rest:

for (int i = 0; i < 30; i++)
{
    System.Threading.Thread.Sleep(100);
    vehicle.Brake();
}

Finally, I turn off the vehicle:

vehicle.Off();

See Listing 5 for the completed Program class implementation.

using VSMFacadePattern.Controllers;

namespace VSMFacadePattern
{
    class Program
    {
        static void Main(string[] args)
        {
            VehicleFacade vehicle = new VehicleFacade(new EngineController(), new TransmissionController(),
                new TractionControlController(), new TachometerController());
            vehicle.Start();

            for (int i = 0; i < 20; i++)
            {
                System.Threading.Thread.Sleep(100);
                vehicle.Accelerate();
            }

            for (int i = 0; i < 30; i++)
            {
                System.Threading.Thread.Sleep(100);
                vehicle.Brake();
            }
           
            vehicle.Off();
        }
    }
}

Listing 5: Program.cs

You should now be able to run the completed application and see the vehicle simulation running in real time, as seen in Figure 1.

[Click on image for larger view.] Figure 1. The complete sample application.

As you can see, the Facade pattern is a very useful design pattern. So useful, in fact, that you may already be practicing the pattern without realizing it. The Facade pattern encourages composition over inheritance, and is a good way to clean up and simply a set of complex subsystems into one more simple, higher-level interface.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube