Printed from www.rmfusion.com A Developer website designed for Developers

Pluggable Adapter Pattern Code Review

Code Download

Define the Adapter Class, Adaptee and Target Classes

The Adaptee class (object) represents the class, in which the behaviour will be modified by the Adapter class (object).

class Adaptee { public Double Precise(Double a, Double b) { return a / b; } }

The Target class (object) represents the class containing the desired class/method behaviour.

class Target { public String Estimate(Int32 i) { return "Estimate is " + (Int32)Math.Round(i/3.0); } }

The Adapter class (object) defines two constructors, each accepting the pluggable adapter to be used.

class Adapter { public Func<Int32, String> Request;
public Adapter(Adaptee adaptee) { Request = delegate(Int32 i) { return "Estimate based on precision is " + (Int32)Math.Round(adaptee.Precise(i, 3)); }; }
public Adapter(Target target) { Request = target.Estimate; } }

Use the Pluggable Adapter Pattern

The Program class creates two instances of the Adapter class (object), passing a different pluggable adapter to each Adapter instance.

class Program { static void Main(string[] args) { Adapter adapter1 = new Adapter(new Adaptee()); Console.WriteLine(adapter1.Request(5));
Adapter adapter2 = new Adapter(new Target()); Console.WriteLine(adapter2.Request(5));
Console.Read(); } }