Sunday, 23 January 2011

Facade pattern vs Adapter pattern

It seems common for programmers to consider the Facade and Adapter patterns very similar or identical (example). However, there is intended to be a subtle difference between these two Gang of Four patterns.

The Adapter pattern is used where you are wrapping an existing object (Adaptee) with a new class (Adapter) that is to be used by an existing client. The Adaptee has a different interface than the client is expecting and we need to fix that. Eg wrapping a set of classes implementing a memory-based filesystem with new classes that fit the file interfaces expected by a client.

The Facade pattern is used to wrap an existing object with a new interface that is easier to use than the existing interface. The consumer of the facade can then be simpler. Eg writing a 'save' method that will open a file, write some data to it, and then close the file.

The save method barely consists of a new algorithm, we're just gluing a few existing file functions together. If there were a new algorithm or some new interfaces and data structures, I would say there was too much code to call it a facade.

I admit that the distinction is small.