Class Adapter Pattern Code Review
Code Download
Define the Adapter Class, Adaptee Class and Target Interface
Define the ITarget interface which defines the class structure that the client will use.
interface ITarget
{
String Request (Int32 i);
}
The Adaptee class (object) represents the class, in which the behaviour will be modified by the Adapter class (object).
class Adaptee
{
public double SpecificRequest (Double a, Double b)
{
return a/b;
}
}
The Adapter class (object) inherits behaviour from both the ITarget interface and the Adaptee class.
class Adapter : Adaptee, ITarget
{
public String Request(Int32 i)
{
return "Rough estimate is " + (Int32)Math.Round(SpecificRequest(i, 3));
}
}
The Request() method wraps the call to the Adaptee method modifying the output for the client.
Use the Class Adapter Pattern
The Program class creates various instances of the Adaptee class (object) and Adapter class (object).
class Program
{
static void Main(string[] args)
{
Adaptee first = new Adaptee( );
Console.Write("Before the new standard\nPrecise reading: ");
Console.WriteLine(first.SpecificRequest(5, 3));
ITarget second = new Adapter();
Console.Write("\nBefore the new standard\nPrecise reading (2): ");
Console.WriteLine((second as Adaptee).SpecificRequest(5, 3));
ITarget third = new Adapter( );
Console.WriteLine("\nMoving to the new standard");
Console.WriteLine(third.Request(5));
Console.Read();
}
}
First, an instance of the Adaptee class (object) is created and a direct method call is made on the class (object). Next, an instance of the Adapter class (object) is created
and a similar call made on the class (object) as before.
Finally, an instance of the Adapter class is created and the adapted method is called.