Skip to content

Instantly share code, notes, and snippets.

@xpmatteo
Last active September 5, 2023 13:07
Show Gist options
  • Save xpmatteo/aff9a10bd830f13586a67c87f8e3a1e0 to your computer and use it in GitHub Desktop.
Save xpmatteo/aff9a10bd830f13586a67c87f8e3a1e0 to your computer and use it in GitHub Desktop.
public class Cat {
private Bird caughtBird;
private boolean isFull = false;
public Cat catchBird(Bird bird) {
if (caughtBird != null) {
throw new RuntimeException("Caught one bird already");
}
caughtBird = bird;
return this;
}
public Cat eat() {
if (caughtBird == null) {
throw new RuntimeException("Must catch a bird first");
}
this.caughtBird = null;
this.isFull = true;
return this;
}
public static void main(String[] args) {
Cat cat = new Cat();
Bird bird = new Bird();
cat.eat().catchBird(bird); // calls out of order;
// throws exception
}
}
public class Story {
public static void main(String[] args) {
Bird bird = new Bird();
HungryCat hungryCat = new HungryCat();
hungryCat.catchBird(bird)
.eat()
.whackOnTheHead()
.catchBird(bird)
.eat()
.whackOnTheHead(); // and repeat
}
}
class HungryCat {
public CatWithPrey catchBird(Bird bird) {
return new CatWithPrey(bird);
}
}
class CatWithPrey {
private Bird caughtBird;
public CatWithPrey(Bird bird) {
this.caughtBird = bird;
}
public FullCat eat() {
return new FullCat();
}
}
class FullCat {
public HungryCat whackOnTheHead() {
System.out.println("Whack! (Coughs up the bird)");
return new HungryCat();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment