Growing with the Web

Facade design pattern

Published , updated
Tags:

The facade design pattern is a very simple pattern that provides a simplified interface to other code that may not be structured the same way.

If we look facade up in the dictionary, this is one of the definitions we get:

An outward appearance that is maintained to conceal a less pleasant or creditable reality.

Google dictionary

This is the primary purpose of the pattern; to conceal a piece of code that isn’t very nice to use and replace it with something better. That’s all it is really, a class that calls code elsewhere.

Benefits

  • Can change a badly-designed or hard to use API into an easy to use API
  • Can merge multiple APIs into a single API
  • If all calls to a function are done through a facade then it is very easy to refactor

Drawbacks

  • Could possibly add unnecessary complexity if overused or used incorrectly

UML diagram

Facade UML diagram

Code example

public class Facade {
    private Class1 class1;
    private Class2 class2;

    public Facade() {
        class1 = new Class1();
        class2 = new Class2();
    }

    public String doSomething() {
        return class1.doSomething() + " " + class2.doSomething();
    }
}

public class Class1 {
    public String doSomething() {
        return "Class1";
    }
}

public class Class2 {
    public String  doSomething() {
        return "Class2";
    }
}
// file: facade.js

'use strict';

var ClassA = require('./class-a.js');
var ClassB = require('./class-b.js');

var Facade = function () {
  this.classA = new ClassA();
  this.classB = new ClassB();
};

Facade.prototype.operation = function () {
  this.classA.operation();
  this.classB.operation();
};

module.exports = Facade;



// file: class-a.js

'use strict';

var ClassA = function () { };

ClassA.prototype.operation = function () {
  console.log('ClassA');
};

module.exports = ClassA;



// file: class-b.js

'use strict';

var ClassB = function () { };

ClassB.prototype.operation = function () {
  console.log('ClassB');
};

module.exports = ClassB;

Usage examples

  • Creating a single consolidated API out of multiple, for example a FastSorter class (the facade) that exposes the functionality of the Quicksort, Merge sort and Heapsort classes I created in recent posts.
  • Simplifying an overly-complex and difficult to use graphics API into a simplified version only containing the functions required for the application.

Like this article?
Subscribe for more!