经常使用instanceof是一种好习惯吗?

经常使用instanceof是一种好习惯吗?,第1张

经常使用instanceof是一种好习惯吗?

假设我正在写一些库存代码

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    }}

这样可以编译并正常工作。但是它错过了面向对象设计的关键思想: 您可以定义父类来做一般有用的事情,而让子类填充特定的重要细节。

以上的替代方法:

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    }}

现在

show()
,在所有清单显示逻辑的子类中,方法都有一个地方可以看。我们如何访问它?简单!

public void showInventory(List<Item> items) {    for (Item item : items) {        item.show();    }}

我们将所有特定于项目的逻辑保留在特定的Item子类中。这使您的代码库更易于维护和扩展。它减少了第一个代码样本中长for-
each循环的认知压力。它

show()
可以在您尚未设计的地方重复使用。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5092458.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存