Link can equip items, strategy design pattern in Java

04 Sep 2019

After reading the first chapter of Head First Design Patterns, I decided to try and implement the Strategy Pattern I learned about by writing my own program in Java. I haven't actually tested this in an editor yet because Java isn't set up on my computer. Literally just wrote this out here.

Character class


public abstract class Character {
  Item item;
  public character() {
  }

  public abstract void introduction();

  public void sleep() {
    System.out.println("zzzzzz");
  }
  public void eat() {
    System.out.println("Omnomnom chicken omnom");
  }

  public void useItem() {
    item.use();
  }

  public void equipItem(Item anItem) {
    item anItem;
  }
}

Link class


public class Link extends Character {
  public Link() {
    item = new Item();
  }

  public void introduction() {
    System.out.println("Hyeeeh kyaaah hyaaaah haa hyet haa haa jum jum haaa");
  }
}

Zelda class


public class Zelda extends Character {
  public Zelda() {
    item = new Item();
  }
  public void introduction() {
    System.out.println("But courage need not be remembered... For it is never forgotten.");
  }
}

Item interface


public interface Item {
  public void use();
}

Sword item class


public class Sword implements Item {
  public void use() {
    System.out.println("Swingy swingy sword sword");
  }
}

Bomb item class


public class Bomb implements Item {
  public void use() {
    System.out.println("You the bomb, no YOU the bomb!");
  }
}

Key item class


public class Key implements Item {
  public void use() {
    System.out.println("da da da da DAAA");
  }
}

Chicken item class


public class Chicken implements Item {
  public void use() {
    System.out.println("Game over");
  }
}

Boomerang item class


public class Boomerang implements Item {
  public void use() {
    System.out.println("Ow, the back of my head");
  }
}

Game character simulator


public class GameCharacterSimulator {
  public static void main(String[] args) {
    Character link = new Link();
    Character zelda = new Zelda();

    zelda.introduction();
    link.introduction();

    link.equipItem(new Key());
    link.useItem();

    link.equipItem(new Sword());
    link.useItem();

    link.equipItem(new Boomerang());
    link.useItem();

    link.equipItem(new Bomb());
    link.useItem();

    link.equipItem(new Chicken());
    link.useItem();
  }
}

Yesterday, I didn't have the first clue about design patterns, and very little experience in Java. Over the last hour, I wrote a custom Legend of Zelda program with a questionable link who is free to equip as many items as he wants. I wrote the program straight into this blog post, without touching a developer environment (besides the one used to write this). That is a huge leap in progress. The book is worth reading.