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

  • Uno Platform Ports Windows Calculator to Linux

    Uno Platform has ported the famed Windows Calculator, open sourced last year, to Linux as part of a continuing "proof point" effort to demonstrate the reach of what it describes as the sole UI offering available to target Windows, WebAssembly, iOS, macOS, Android and Linux with single-codebase applications coded in C# and XAML.

  • ASP.NET Core OData 8 Preview Supports .NET 5, but with Breaking Changes

    ASP.NET Core OData, which debuted in July 2018, is out in a v8.0 preview that for the first time supports the upcoming .NET 5 milestone release.

  • VS Code Java Team Details 5 Best Dev Practices

    Microsoft's Visual Studio Code team for Java development added a new Coding Pack for Java installer and detailed best practices for setting up a development environment.

  • Binary Classification Using PyTorch: Defining a Network

    Dr. James McCaffrey of Microsoft Research tackles how to define a network in the second of a series of four articles that present a complete end-to-end production-quality example of binary classification using a PyTorch neural network, including a full Python code sample and data files.

  • Blazor Debugging Boosted in .NET 5 RC 2

    In highlighting updates to ASP.NET Core in the just-launched second and final Release Candidate of .NET 5, Microsoft pointed out better debugging for Blazor, the red-hot project that allows for C# coding of web projects.

Upcoming Events