Adapter Design Pattern

Go back

Aliases πŸ“Œ: Wrapper, Translator

Description πŸ“š: It's common in software development to have software that behaves in a specific way and a client software that requires to use it in another specific way.

The Adapter is a class that connects the two.

Advantages βœ…

  • Allow two programs/classes/... to interact with each other

Disadvantages 🚫

  • Increase the amount of code to write/maintain

Notes πŸ“

  • For instance, a webapp and a payment API

Java implementation

Assuming, you defined that characters could only attack:

public class Character {
    public void attack() {
        System.out.println("Character attacks!");
    }
}

But, the game, the client that was externally implemented, was expecting characters to be able to attack and defend:

public interface RPGCharacter {
    void performAttack();
    void performDefense();
}
public class RPGGame {
    private final RPGCharacter character;

    public RPGGame(RPGCharacter character) {
        this.character = character;
    }

    public void battle() {
        character.performAttack();
        // Perform new RPG logic here...
        character.performDefense();
    }
}

Then, we need to create an adapter to be able to use it:

public class CharacterAdapter implements RPGCharacter {
    private final Character character;

    public CharacterAdapter(Character character) {
        this.character = character;
    }

    @Override
    public void performAttack() {
        character.attack();
    }

    @Override
    public void performDefense() {
        // do some implementation
        // so that it works
    }
}
public class Main {
    public static void main(String[] args) {
        CharacterAdapter character = new CharacterAdapter(new Character());
        RPGGame game = new RPGGame(character);
        game.battle();
    }
}

πŸ‘‰ Here, we could also directly edit Character to implement RPGCharacter as it is an interface (it could have been a class, a final class...).