Facade is a struc­tur­al design pat­tern that pro­vides a sim­pli­fied inter­face to a library, a frame­work, or any other com­plex set of classes.

Problem: Spaghetti design!

Solution: subsystem interface object

<aside>

Applicability

image.png

When you call a shop to place a phone order, an oper­a­tor is your facade to all ser­vices and depart­ments of the shop. The oper­a­tor pro­vides you with a sim­ple voice inter­face to the order­ing sys­tem, pay­ment gate­ways, and var­i­ous deliv­ery services.

When you call a shop to place a phone order, an oper­a­tor is your facade to all ser­vices and depart­ments of the shop. The oper­a­tor pro­vides you with a sim­ple voice inter­face to the order­ing sys­tem, pay­ment gate­ways, and var­i­ous deliv­ery services.

Structure

image.png

  1. The Facade pro­vides con­ve­nient access to a par­tic­u­lar part of the sub­sys­tem’s func­tion­al­i­ty. It knows where to direct the client’s request and how to oper­ate all the mov­ing parts.
  2. An Addi­tion­al Facade class can be cre­at­ed to pre­vent pol­lut­ing a sin­gle facade with unre­lat­ed fea­tures that might make it yet anoth­er com­plex struc­ture. Addi­tion­al facades can be used by both clients and other facades.
  3. The Com­plex Sub­sys­tem con­sists of dozens of var­i­ous objects. To make them all do some­thing mean­ing­ful, you have to dive deep into the sub­sys­tem’s imple­men­ta­tion details, such as ini­tial­iz­ing objects in the cor­rect order and sup­ply­ing them with data in the prop­er format.

Sub­sys­tem class­es aren’t aware of the facade’s exis­tence. They oper­ate with­in the sys­tem and work with each other directly.

  1. The Client uses the facade instead of call­ing the sub­sys­tem objects directly.

<aside>

How to Implement

  1. Check whether it’s pos­si­ble to pro­vide a sim­pler inter­face than what an exist­ing sub­sys­tem already pro­vides. You’re on the right track if this inter­face makes the client code inde­pen­dent from many of the sub­sys­tem’s classes.
  2. Declare and imple­ment this inter­face in a new facade class. The facade should redi­rect the calls from the client code to appro­pri­ate objects of the sub­sys­tem. The facade should be respon­si­ble for ini­tial­iz­ing the sub­sys­tem and man­ag­ing its fur­ther life cycle unless the client code already does this.
  3. To get the full ben­e­fit from the pat­tern, make all the client code com­mu­ni­cate with the sub­sys­tem only via the facade. Now the client code is pro­tect­ed from any changes in the sub­sys­tem code. For exam­ple, when a sub­sys­tem gets upgrad­ed to a new ver­sion, you will only need to mod­i­fy the code in the facade.
  4. If the facade becomes too big, con­sid­er extract­ing part of its behav­ior to a new, refined facade class. </aside>