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.
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].