Design Patterns in Action(5)- Facade

A series of programming design patterns illustration with examples with JavaScript/Python

Photo by Shardar Tarikul Islam on Unsplash

Simply put, the facade pattern is used to serve as a high level interface for the client to interact with a set of more complex subsystems. It hides the implementation details of the underlying systems and exposes an unified, sometimes even single method to the client.

The benefits of it are:

Facade can be easily confused with Adapter, or Decorator pattern. But essentially:

Let’s take a look at an example in Python. The code is quite explanatory.

class Oven:
def wait_for_bake(self, bake_in_min):
self.bake_in_min = bake_in_min


class Mixer:
def choose_flour(self, flour_kind):
self.flour_kind = flour_kind

def wait_for_rise(self, rise_in_min):
self.rise_in_min = rise_in_min


class Shelf:
def label_bread(self):
pass


class BreadFacade:
def __init__(self):
self.mixer = Mixer()
self.oven = Oven()
self.shelf = Shelf()

def produce(self, flour_kind, rise_in_min, bake_in_min):
self.mixer.choose_flour(flour_kind)
self.mixer.wait_for_rise(rise_in_min)
self.oven.wait_for_bake(bake_in_min)
self.shelf.label_bread()


bread = BreadFacade()
bread.produce("wholemeal", 60, 120)

And here is the implementation in JavaScript:

class Oven {
wait_for_bake(bake_in_min) {
this.bake_in_min = bake_in_min;
return;
}
}

class Mixer {
choose_flour(flour_kind) {
this.flour_kind = flour_kind;
return;
}

wait_for_rise(rise_in_min) {
this.rise_in_min = rise_in_min;
return;
}
}

class Shelf {
label_bread() {
return;
}
}

class BreadFacade {
constructor() {
this.mixer = new Mixer();
this.oven = new Oven();
this.shelf = new Shelf();
}

produce(flour_kind, rise_in_min, bake_in_min) {
this.mixer.choose_flour(flour_kind);
this.mixer.wait_for_rise(rise_in_min);
this.oven.wait_for_bake(bake_in_min);
this.shelf.label_bread();
}
}

let bread = new BreadFacade();
bread.produce("wholemeal", 60, 120);

That’s so much of it!

Happy Reading!

Hi :)