In real world applications, a subsystem could consist of a large number of classes. Clients of a subsystem may need to interact with a number of subsystem classes for their needs. This kind of direct interaction of clients with subsystem classes leads to a high degree of coupling between the client objects and the subsystem.
Whenever a subsystem class undergoes a change, such as a change in its interface, all of its dependent client classes may get affected.
The Façade pattern is useful in such situations. The Façade pattern provides a higher level, simplified interface for a subsystem resulting in reduced complexity and dependency. This in turn makes the subsystem usage easier and more manageable.
With a Façade object in place, clients interact with the Façade object instead of interacting directly with subsystem classes. The Façade object takes up the responsibility of interacting with the subsystem classes.
Example
Let us build an application that:
- Accepts customer details (account, address and credit card details)
- Validates the input data
- Saves the input data to appropriate data files
In order to validate and save the input data, the client AccountManager would:
- Create Account, Address and CreditCard objects
- Validate the input data using these objects
- Save the input data using these objects
Before applying the facade
Applying the Façade pattern, let us define a Façade class CustomerFacade that offers a higher level, simplified interface to the subsystem consisting of customer data processing classes (Address, Account and CreditCard).
The CustomerFacade class offers a higher level business service in the form of the saveCustomerData method. Instead of interacting with each of the subsystem components directly, the client AccountManager can make use of the higher level, more simplified interface offered by the CustomerFacade object to validate and save the input customer data.
Here are few notes to consider while applying the Façade pattern:
- A façade should not be designed to provide any additional functionality.
- Never return subsystem components from Façade methods to clients. As an example, having a method as CreditCard getCreditCard() , would expose the subsystem to clients and the application may not be able o realize the full benefits of using the Façade pattern.
No comments:
Post a Comment