Este exercício saiu no teste de 2012/01/30.
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();
}
}
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).