经常使用instanceof是一种好习惯吗? [英] Is it good practice to often use instanceof?

查看:108
本文介绍了经常使用instanceof是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情景。我正在写与游戏相关的代码。在该游戏中,播放器(它也是一个类)有一个 Item 的列表。还有其他类型的项继承自 Item ,例如 ContainerItem DurableItem WeaponItem

The scenario. I'm writting game-related code. In that game a Player(its also a class) has a list of Item. There are other types of items that inherit from Item, for example ContainerItem, DurableItem or WeaponItem.

显然我只需要<$ c $非常方便C>列表与LT;项目> 。但是当我获得玩家物品时,我唯一的方法是使用 instanceof 关键字来区分什么类型的物品。我敢肯定我已经读过,依赖它是不好的做法。

Obviously it is very conveniant for me to just have List<Item>. But when I get the players items, the only way for me to distinguish between what type of item is by using the instanceof keyword. I'm sure I've read that reliaing on it is bad practice.

在这种情况下可以使用它吗?或者我应该重新考虑我的所有结构吗?

Is it ok to use it in this case? Or should I rethink all of my structure?

推荐答案

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

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.

上述替代方法:

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()方法。我们如何访问它?简单!

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();
    }
}

我们将所有特定于项目的逻辑保留在特定的内部项子类。这使您的代码库更易于维护和扩展。它减少了第一个代码样本中每个循环的长期认知压力。它准备 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.

这篇关于经常使用instanceof是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆