Adapter Pattern
Adapter Pattern
Continuing the tour in the structural patterns I'm going to introduce the adapter pattern.
You can read my previous posts on structural patterns here:
Decorator pattern
Proxy pattern
Facade pattern
The Adapter Pattern
The adapter pattern helps us to convert an interface of a class into another
interface that we need. It helps us to adapt old systems to new systems
without the need to rewrite the old systems. Also, adapter pattern enables
classes to work together even though they have an incompatible interfaces.
For a UML diagram of the pattern go to dofactory site.
How does it Work?
One way to implement the adapter pattern includes 3 participants -
an interface, an adaptee and an adapter. The interface defines the
operations we need in the adapter. The adaptee has it's original operations.
The adapter class inherits the adaptee class and implements the interface
by using the adaptee operations.
Another way to implement the adapter also includes 3 participants -
the class with operations to inherit (which replace the interface), an adaptee and an adapter.
In this case The class defines virtual methods, the adapter class inherit the
class and holds the adaptee as member. The adapter class overrides the class' virtual
methods and use the adaptee operations inside them.
Example in C#
Lets look at a simple example of the first way:
#region Interface
public interface IOperation
{
#region Methods
void Fly();
#endregion
}
#endregion
#region Adaptee
public class Car
{
#region Methods
public void Drive()
{
// do the operation of drive
}
#endregion
}
#endregion
#region Adapter
public class FlyingCar : Car, IOperation
{
#region IOperation Members
public void Fly()
{
// calling the drive method of the Car
this.Drive();
}
#endregion
}
#endregion
Summary
The adapter pattern is useful for places where you have a class with an operation
that you want to use but the interface of the class isn't compatible with the
interface that you need.
In the next post in this series I'll write about the composite pattern.