Last active
September 5, 2023 13:07
-
-
Save xpmatteo/aff9a10bd830f13586a67c87f8e3a1e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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