Giving a slip to Design pattern 6, the command pattern
Adapter pattern - Converts the interface of a class into another interface clients expect. Lets classes work together that couldn't otherwise because of incompatible interfaces.
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.
Adapter pattern - Typical example is using a adapter class to adapt a Enumeration class of Java to that of Iterator class.
Adapter pattern has three interfaces -
- The Target interface
- The Adapter interface
- The Adaptee interface
Example: Lets have a Duck interface
interface Duck{
void quack();
void fly();
}
interface Turkey {
void gobble();
void shortFly();
}
class DuckAdapter implements Duck{
Turkey turkey;
DuckAdapter(Turkey turkey){
this.turkey = turkey;
}
void quack(){
turkey.gobble();
}
void fly(){
turkey.shortFly();
}
}
In the above example, the DuckAdapter adapts to the Turkey(Adaptee). The client is not aware that the turkey's methods are getting executed.
Adapter Patterns are of two forms - Class Adapters and Object Adapter. Class Adapter require multiple inheritance.
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. A facade decouples a client from a complex subsystem.
For example, taking the example of home theatre system. It comprises of many subsystems such as a projector system, sound system, etcetra. If we were to do a simple job of watching a movie using the dvd player, and we take the subsystems into account, we end up creating multiple classes in a single class. Implementing Facade requires we compose the facade with its subsystem and use delegation to perform the work of the facade.
Use an Adapter, when you need to use an existing class and its interface is not the one you need.
Use a facade, when you need to simplify and unify a large interface or complex set of interfaces.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment