Last active
June 6, 2022 14:36
-
-
Save GeePawHill/23669f85377b81a9cf5f2694ed495e6b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| A classic "switch on type" in Java. The draw method interrogates its parameter's class, and decides what to do as a resuilt. | |
| interfact Thing { } | |
| class Wall implemnts Thing { } | |
| class Door implements Thing { } | |
| class Chest implements Thing { } | |
| void draw(Thing thing) { | |
| if(thing instanceof(Wall) drawWall(thing) | |
| else if(thing instanceof(Door) drawDoor(thing) | |
| else if(thing instanceOf(Chest) drawChest(thing) | |
| else drawBlank(thing) | |
| } | |
| This is a switch on type, too. This time, it decided what to do not based on the particular sub-class of Thing, but on a type field inside Thing. | |
| class Thing { | |
| public final int kind; | |
| } | |
| void draw(Thing thing) { | |
| switch(thing.kind) { | |
| case WALL: drawWall(thing); break; | |
| case DOOR: drawDoor(thing); break; | |
| case CHEST: drawChest(thing); break; | |
| default: drawBlank(thing) | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment