C# Adapter Design Pattern

Next pattern on my list is called adapter. This is another type of structural pattern. Adapter is the object which lets two mutually incompatible interfaces communicate with each other. Adapter pattern acts as a bridge between two incompatible interfaces. This pattern involves a single class called adapter which is responsible for communication between two independent or incompatible interfaces.

 

248-goravel-uk-swiss-switzerland-adapter-plugMost popular example that illustrate this problem is electrical socket adapter plug that changes. For example UK is using different sockets than rest of EU. That’s forcing people to use adapters.

 

 

To demonstrate this pattern I’ll use simplified example of game mechanics that have Interface of enemies, but one of the enemies is different than others and don’t have implementation of Attack method.  Instead this specific enemy is casting spells.

UML diagram

l

 

Lest begin by crating SpecialEnemy class that’s using CastSpell method. That is called Adaptee and will be used later in Adapter Class.

class SpecialEnemy
{
  public string CastSpell()
  {
     return "using spell";
  }

I will use return string to simplify the process.

Next lest create Interface IEnemy for managing the enemies behaviour, in this case it’s only one method for Attack.

interface IEnemy
{
  string Attack();

Now we need to inherit this interface by EnemyAdapter Class that will connect both pieces together.

class EnemyAdapter: IEnemy
{
  SpecialEnemy e = new SpecialEnemy();
  public string Attack()
  {
     return e.CastSpell();
  }

We need to add reference to the Adaptee in order to have access to CastSpell method. This way we can use the Attack Method without implementation it SpecialEnemy Adaptee.

Last step is to call the Enemy Attack method in client Class.

class Program
{
  static void Main(string[] args)
  {
    IEnemy enemy = new EnemyAdapter();
    Console.WriteLine(enemy.Attack());
    Console.ReadLine();
  }

As an output we get “using spell” string displayed.

This example was oversimplified, but it demonstrates the idea behind this simple pattern. I hope you will find it useful. In next article I’ll demonstrate another exciting creational Pattern called Builder. Stay Awesome!