The facade pattern is a software engineering design pattern commonly used with Object-oriented programming.
A facade is an object that provides a simplified interface to a larger body of code, such as a class library . A facade can:
- make a software library easier to use and understand, since the facade has convenient methods for common tasks;
- make code that uses the library more readable, for the same reason;
- reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
- wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).
Structure
Example
Java provides a set of classes that connect to databases using an interface called JDBC. You can connect to any database for which the manufacturer has provided a JDBC connection class -- almost every database on he market. Some databases have direct connections using JDBC and a few allow connection to ODBC driver using the JDBCODBC bridge class.
These database classes in the java.sql package provide an excellent example of a set of quite low level classes that interact in a convoluted manner.
To connect to a database, you use an instance of the Connection class. Then, to find out the names of the database tables and fields, you need to get an instance of the DatabaseMetadata class from the Connection. Next, to issue a query, you compose the SQL query string and use the Connection to create a Statement class. By executing the statement, you obtain a ResultSet class, and to find out the names of the column rows in that ResultSet, you need to obtain an instance of the ResultsetMetadata class. Thus, it can be quite difficult to juggle all of these classes and since most of the calls to their methods throw Exceptions, the coding can be messy at least.
Consequences of the Façade
The Façade pattern shields clients from complex subsystem components and provides a simpler programming interface for the general user. However, it does not prevent the advanced user from going to the deeper, more complex classes when necessary.
In addition, the Façade allows you to make changes in the underlying subsystems without requiring changes in the client code, and reduces compilation dependencies.