Let's say I am writing some inventory code:
public void showInventory(List<Item> items) {
for (Item item : items) {
if (item instanceof ContainerItem) {
// container display logic here
}
else if (item instanceof WeaponItem) {
// weapon display logic here
}
// etc etc
}
}
That will compile and work just fine. But it misses out on a key idea of object oriented design: You can define parent classes to do general useful things, and have child classes fill in specific, important details.
Alternate approach to above:
abstract class Item {
// insert methods that act exactly the same for all items here
// now define one that subclasses must fill in themselves
public abstract void show()
}
class ContainerItem extends Item {
@Override public void show() {
// container display logic here instead
}
}
class WeaponItem extends Item {
@Override public void show() {
// weapon display logic here instead
}
}
Now we have one place to look, the show()
method, in all our child classes for inventory display logic. How do we access it? Easy!
public void showInventory(List<Item> items) {
for (Item item : items) {
item.show();
}
}
We are keeping all the item-specific logic inside specific Item subclasses. This makes your codebase easier to maintain and extend. It reduces the cognitive strain of the long for-each loop in the first code sample. And it readies show()
to be reusable in places you haven't even designed yet.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…