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

Two Way Adapter Pattern Code Review

Code Download

Define the AirCraft Interface and Handler Object

Define the IAircraft interface to be used as the target interface, which represents the first adapter.

interface IAircraft { bool Airbourne { get; } void TakeOff(); int Height { get; } }

The Aircraft class (object) represents a class to be adapted.

sealed class Aircraft : IAircraft { public Aircraft() { this.Height = 0; this.Airbourne = false; }
public bool Airbourne { get; private set; } public int Height { get; private set; }
public void TakeOff() { Console.WriteLine("Aircraft engine takeoff!"); this.Airbourne = true; this.Height = 200; } }

Define the Seacraft Interface and Handler Object

Define the ISeacraft interface to be used as the target interface, which represents the second adapter.

interface IAircraft { bool Airbourne { get; } void TakeOff(); int Height { get; } }

The Seacraft class (object) represents a class to be adapted.

sealed class Aircraft : IAircraft { public Aircraft() { this.Height = 0; this.Airbourne = false; }
public bool Airbourne { get; private set; } public int Height { get; private set; }
public void TakeOff() { Console.WriteLine("Aircraft engine takeoff!"); this.Airbourne = true; this.Height = 200; } }

Define the Seabird Two Way Adapter Object

The SeabirdAdapter class (object) represents the two-way adapter class, and is the common interface between the two adapted classes (objects).

class SeabirdAdapter : Seacraft, IAircraft { public Int32 Height { get; private set; }
public void TakeOff() { while (!this.Airbourne) { this.IncreaseRevs(); } }
public Boolean Airbourne { get { return (this.Height > 50); } }
public override void IncreaseRevs() { base.IncreaseRevs();
if (this.Speed > 40) { this.Height += 100; } } }

Use the Two Way Adapter Pattern

The Program class creates an instance of both the class adapter (Aircraft) and the two-way adapter (SeabirdAdapter).

class Program { static void Main(string[] args) { Console.WriteLine("Experiment 1: test the aircraft engine"); IAircraft aircraft = new Aircraft(); aircraft.TakeOff(); if (aircraft.Airbourne) { Console.WriteLine(String.Format("The aircraft engine is fine, flying at {0} meters.", aircraft.Height)); }
Console.WriteLine("\nExperiment 2: Use the engine in the Seabird"); IAircraft seabird = new SeabirdAdapter(); seabird.TakeOff(); Console.WriteLine("The Seabird took off");
Console.WriteLine("\nExperiment 3: Increase the speed of the Seabird:"); (seabird as SeabirdAdapter).IncreaseRevs(); (seabird as SeabirdAdapter).IncreaseRevs(); if (seabird.Airbourne) { Console.WriteLine(String.Format("Seabird flying at height {0} meters and speed {1} knots.", seabird.Height, (seabird as ISeacraft).Speed)); } Console.WriteLine("Experiments successful; the Seabird flies!");
Console.ReadLine(); } }