Adapter pattern
Adapter is designed to change an interface to another interface expected by client. which makes the uncompatible types work together.
When we use this pattern
- We want to reuse the code designed before, which has the similar functionality to our current situation. but they are not compatible.
- When we maintain our system, we need some optimization, but some of them are not compatible.
we can find the core for this pattern is to reuse the code when the former interface is not compatible with the current one and dedicated to resove the compatible issue.
Roles in this pattern.
- Target: in which our current interfaces and functions are defined.
- Client: the one that uses the target and communicates with the target.
- Adaptee: the exsiting interface which is uncompatible with the target but with the similar function to the target. we got to use a adapter to adapt it into our target.
- Adaper: as its name shows.
Structure:
there are two structures for this pattern:
- Class adapter: this is implemented by letting the adapter inherit both both the target and the adaptee. I am not so into this stucture while the C# doesnot support the multiple inheritance.
- Object adapter: this is implemented by letting the adapter inherit the target but have a reference of adaptee. Personally speaking i like this structure
A small code designed(C#) is to demonstrate this pattern(Object adapter):
namespace Adapter
{
public class Target
{
public virtual void DoSomethingForTarget()
{
//do something here
}
}
public class Adaptee
{
public void DoSomethingForAdaptee()
{
//do something here
}
}
public class Adapter:Target
{
private Adaptee adaptee = new Adaptee();//got a reference of adaptee
public override void DoSomethingForTarget()
{
adaptee.DoSomethingForAdaptee();//here adapt the adaptee to the target exactly
}
}
public class Client
{
static void Main(string[] args)
{
Target myTarget = new Adapter();
myTarget.DoSomethingForTarget();
}
}
}
this pattern is simple but i did not ever use it in the real project.