Facade Pattern
The Facade pattern is a software design pattern that provides a unified interface to a set of interfaces in a subsystem. This pattern defines a high-level interface that makes the subsystem easier to use. Facade is often used when a system is complex or difficult to understand because the system has a large number of interdependent classes or its source code is unavailable.
The Facade pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class which contains a set of members required by the client. These members access the system on behalf of the facade client and hide the implementation details.
Let's take an example. Assume we have a subsystem that provides operation like read
, write
and close
as individual operations for a File
system:
class FileReader {
public void read() {
System.out.println("Reading file");
}
}
class FileWriter {
public void write() {
System.out.println("Writing to file");
}
}
class FileCloser {
public void close() {
System.out.println("Closing file");
}
}
Using these classes individually can be complex for a client. To simplify, we introduce a FileFacade
:
class FileFacade {
private FileReader fileReader;
private FileWriter fileWriter;
private FileCloser fileCloser;
public FileFacade() {
fileReader = new FileReader();
fileWriter = new FileWriter();
fileCloser = new FileCloser();
}
public void performOperations() {
fileReader.read();
fileWriter.write();
fileCloser.close();
}
}
Here, FileFacade
provides a higher-level interface to the subsystem making it easier for clients to use:
class Client {
public static void main(String[] args) {
FileFacade fileFacade = new FileFacade();
fileFacade.performOperations();
}
}
In summary, the Facade pattern provides an interface which shields clients from complex functionality in subsystems. It ties the subsystems together and promotes subsystem independence and portability.