Friday, February 10, 2012

The Adapter Pattern

Definition : The adapter pattern is used to match one interface with the other.

Problem : In the below example I have a console application based on FarmAnimals. I would like to build a collection of farm animals with several capabilities. Some of these capabilities I wish to implement on my own , other I hope to be able to make use of using third party libraries with existing functionality. I have found one such library called the ZooLib, but the ZooLib animal implementation a very different interface.

Analysis : My console application FarmAnimals consists of a concrete class called goat that implements the IFarmAnimal interface. The IFarmAnimal interface specifies a method getDietaryType.

The ZooLib assembly consists of a concrete function getFamily, that I would like to use in my console application FarmAnimals. But since my goat class implements IFarmAnimal and the getFamily which is part of the MountainGoat concerete class which implements the interface IZooAnimals which are incompatible interfaces.

Solution : I introduce an abstract base class called ZooAnimalAdapter. ZooAnimalAdapter impliments both interfaces, it delegates all my IFarmAnimal operations to the concrete subclasses and builds wrappers around the IFarmAnimal.

Code

The below is my FarmAnimal application

class Program
{
static void Main(string[] args)
{
Goat g = new Goat();
g.getFamily();
g.getDietaryType();

Console.ReadKey();
}
}

public abstract class ZooAnimalAdapter:IFarmAnimal,IZooAnimal
{
public abstract void getDietaryType();

public void getFamily()
{
IZooAnimal za = new MountainGoat();
za.getFamily();
}
}

public interface IFarmAnimal
{
void getDietaryType();
}



Below are the contents of the ZooLib library




public interface IZooAnimal
{
void getFamily();
}

public class MountainGoat : IZooAnimal
{
public void getFamily()
{
Console.WriteLine(" Family : Bovidae");
}
}

No comments: