AdapterPattern

Pros

  • Allows two different classes with incomaptible interfaces to work together
  • Increases code reusability

Cons

  • Slight overhead from having to go through an adapter

Example Explanation

This example uses object adapter instead of class adapter to follow the composition over inheritance principle.

Mob - Interface that forms the requirements for NewMob and MobAdapter

LegacyMob - Old mob that does not follow the interface Mob's requirements

MobAdapter - Uses delegation to allow a LegacyMob to follow an interface's requirements

import java.util.*;
class Main {
  public static void main(String[] args) {

    NewMob mobOne = new NewMob(20, 7.3, 5);

    LegacyMob mobTwoOld = new LegacyMob(33, 5, 10);

    List<Mob> mobList = new ArrayList<Mob>();

    mobList.add(mobOne);
    mobList.add(new MobAdapter(mobTwoOld));

    System.out.println(mobList); //[[20, 7.3, 5], [33, 5.0, 10]]

  }
}

class LegacyMob{
  int hitpoints;
  int attack;
  int level;

  public LegacyMob(int hitpoints, int attack, int level){
    this.hitpoints = hitpoints;
    this.attack = attack;
    this.level = level;
  }

  public int getHitpoints(){ return hitpoints; }
  public int getAttack(){ return attack; }
  public int getLevel(){ return level; }
}

class NewMob implements Mob{

  int life;
  int level;
  double damage;

  public NewMob(int life, double damage, int level){
    this.life = life;
    this.level = level;
    this.damage = damage;
  }

  public int getLife(){ return life; }
  public double getDamage(){ return damage;}
  public int getLevel(){ return level; }

  @Override
  public String toString(){
    return "["+life+", "+damage+", "+level+"]";
  }
}

class MobAdapter implements Mob{

  LegacyMob legacyMob;

  public MobAdapter(LegacyMob legacyMob){
    this.legacyMob = legacyMob;
  }

  public int getLife(){ return legacyMob.getHitpoints(); }
  public double getDamage(){ return legacyMob.getAttack();}
  public int getLevel(){ return legacyMob.getLevel(); }

  @Override
  public String toString(){
    return "["+getLife()+", "+getDamage()+", "+getLevel()+"]";
  }

}

interface Mob{
  public int getLife();
  public double getDamage();
  public int getLevel();
  public String toString();
}

Extra Resources

https://javapapers.com/design-patterns/adapter-pattern/

https://refactoring.guru/design-patterns/adapter

results matching ""

    No results matching ""