Strategy Pattern (padrão de desenho)/Galinha com fome

From Wiki**3

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Este exercício saiu no teste de 2012/01/30.

Problema

Considere o seguinte programa em Java:

public class Chicken {
  private Stomach _stomach = new Hungry();
  public void eat()   { _stomach.eat();   }
  public void sleep() { _stomach.sleep(); }
  public void setMood(Stomach stomach) { _stomach = stomach; }
}

public abstract class Stomach {
  protected Stomach() { System.out.println("Hmmm..."); }
  public void eat()   { System.out.println("..."); }
  public void sleep() { System.out.println("..."); }
}

public class Hungry extends Stomach {
  public Hungry()     { System.out.println("I'm hungry!!"); }
  public void eat()   { System.out.println("Eating..."); }
  public void sleep() { System.out.println("I'm too hungry to sleep!!"); }
}

public class Sated extends Stomach {
  public Sated()      { System.out.println("I'm sleepy!!"); }
  public void eat()   { System.out.println("I'm not hungry..."); }
  public void sleep() { System.out.println("ZzZz..."); }
}

public class Farm {
  public static void main(String args[]) {
    Chicken chicken = new Chicken();
    chicken.eat();
    chicken.setMood(new Sated());
    chicken.sleep();
    chicken.setMood(new Hungry());
    chicken.sleep();
  }
}
  1. Que resultado se obtém quando se executa o seguinte programa? (represente mudanças de linha com \n)
  2. Que padrão de desenho é usado no programa?

Solução

O resultado obtido é o seguinte (trivial):

Hmmm...\nI'm hungry!!\nEating...\nHmmm...\nI'm sleepy!!\nZzZz...\nHmmm...\nI'm hungry!!\nI'm too hungry to sleep!!

O pradrão usado é o Strategy (corresponde à delegação de comportamento no conceito Stomach).