Facade Pattern

The Facade Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Bates and SierraHead First Design Patterns

Class diagram

/images/posts/design-patterns/facade_pattern.png

The Facade is a unified interface easily usable by the client which doesn’t dialog anymore with the complex subsytem.

##Design Principle Principle of Least Knowledge, talk only to you immediate friends.

  • Loosely coupled system. Prevent from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade on the other parts.
  • Fragile system. It happens when there are a lot of dependencies between many classes.

##Key Points

  • Only one friend. The client has only one friend, the facade.
  • Decoupling. Allow to decouple client implementation from any subsystem. Coding to the facade, rather than to the subystem, allows the client code to not change every time the subsystem changes, just the facade has to update.
  • Delegation. Implementing the facade requires to compose the facade with its subsystem and use delegation to perform the work.
  • Subsytem update. The update doesn’t affect the client.
  • Additional facade. If the subsystem gets too complex additional facade could be introduced to form layers of subsystems.
  • Not encapsulate. The Facade doesn’t encapsulate the classes but provides a simpler interface to the client. The subsystem classes can be still used by the client to achieve some low levels functionality.
  • Many facades. Given a subsystem many facades can be created.

##Comparison

  • Wrap multiple classes. Both can wrap multiple classes.
  • Facade
    • Simplify an interface.
    • Decouple a client from a subsystem of components
    • Subsystem classes are still available to the client for low level functionality.
  • Adapter
    • Convert an interface into something different, something the client is expecting.
    • Encapsulate the subsystem in order to hide it to the client which will use just the adapter interface.