Posts Tagged ‘vendor class library’

The Facade Pattern – Don’t Talk to Strangers

June 18, 2009 2 comments

Ben Yoder the Facade Pattern

June 19th 2009 | Ben Yoder

The Facade Pattern – Don’t Talk to Strangers

The Facade and Adapter patterns are two closely related and easily confused designs. Both patterns create a layer between two interacting classes but the objective of each is significantly different.

While the Adapter pattern encapsulates the communication between two classes, the goal of the Facade pattern is to simplify wiring in a set of actions leveraging a complex subsystem of code, such as a group of legacy classes, or a third party vendor’s class library or API. If you ever need to integrate a third party system or an open source library and find yourself entangled in outside dependencies and overly-complicated sets of method calls, a Facade refactoring can help you.

There’s a good chance you’ve created a facade pattern on occasion without realizing it. As an oversimplified mechanical analogy—when you start a car, you don’t go through the separate steps of combining an electrical spark with gasoline in the engine cylinder while simultaneously cranking the engine to achieve compression. Instead of worrying about the complicated series of steps involved in making a car start, you simply turn a key which creates some magical action that starts a car.

The engine ignition switch is our facade class. It hides the ugly workings of the engine from us and we simply say “Make Go” and it works.

    public class SparkPlug
        public void Spark(){…}
    public class FuelPump
        public void PumpFuel() {…}
        public void ShutOffFuel(){…}
    public class Starter
        public void Crank() {…}
    //Encapsulates starting logic
    public class IgnitionSwitchFacade
        public void StartEngine()
            FuelPump pump = new FuelPump();
            SparkPlug plug = new SparkPlug();
            Starter starter = new Starter();
    //Client Code that interfaces with the Facade
    class You
        static void Main(string[] args)
            IgnitionSwitchFacade ignitionSwitch = new IgnitionSwitchFacade();

This bit of code is contrived, but it demonstrates what’s so powerful about the Facade pattern and how it differs from the Adapter.

While the Adapter is concerned about sitting between the client and an interface, the Facade’s aim is to encapsulate common logic or instructions of a subsystem for the client’s consumption.

The goal of the Facade is simplicity. It provides a common gateway to the class library which can be easily modified and called rather than dealing directly with the logic and classes it hides.

Read David Cooksey’s The Adapter Pattern, A Code Diplomat

Ben Yoder is a Senior .NET Consultant at Thycotic Software, an agile software consulting and product development company based in Washington DC. Secret Server is our flagship password management software product.