Major Players of this pattern are:
- Target (An abstract base class for the adapters)
- Adapter
- Adaptee (The older piece of code)
- Client
The idea is common in .NET framework, for example every time you use a legacy COM component and import it into .NET, what happens is that the imported code will be wrapped inside an adapter .NET class (interop assembly) that translates the functionality and patterns that were common in the COM era to the .NET era. For example if a method fails to operate properly in COM, it will return a non-zero HRESULT value; this functionality is changed by the adapter (interop assembly) to raise an exception instead (which is more common in .NET)
class Program
{
static void Main(string[] args)
{
//The client has no idea about the older code
Target target = new Adapter();
target.NewerMethod();
}
}
class Target
{
public virtual void NewerMethod()
{
Console.WriteLine("Called Target-NewerMethod");
}
}
// The actual "Adapter"
class Adapter : Target
{
//Points to the older piece of code
private Adaptee adaptee = new Adaptee();
public override void NewerMethod()
{
adaptee.OlderMethod();
}
}
// "Adaptee"
class Adaptee
{
public void OlderMethod()
{
Console.WriteLine("Called OlderMethod");
}
}
No comments:
Post a Comment