Java:在以下代码中使用命令模式 [英] Java: using command pattern in the following code

查看:60
本文介绍了Java:在以下代码中使用命令模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似以下代码:

void processObjectRecursively(Object obj)
{
    Field[] fields = obj.getClass().getDeclaredFields();

    for(Field field : fields)
    {
        FieldType type = FieldUtils.getType(field); // FieldType is enum
        Object value = field.get(obj);

        switch(type)
        {
            case A:
            processObjectRecursively(value);
            continue;

            case LIST:
            processList((List<?>)value);
            continue;

            case B:
            processB(value);
            continue;

            case C:
            processC(value);
            continue;
        }
    }
}

void processList(List<?> list)
{
    for(Object obj : list)
    {
        processObjectRecursively(obj);
    }
}

void processB(Object obj)
{
    // do something
}

void processC(Object obj)
{
    // do something
}

现在。我不喜欢这种长开关盒。因此,我正在考虑创建命令并在其中填充地图,其中类型是键,值是其对应的命令对象。这样,该方法将类似于:

Now. I don't like this long switch case. So I'm thinking of creating commands and populating a Map with them where the type is the key and the value is its corresponding command object. With this, the method would look something like:

void processObjectRecursively(Object obj)
{
    Field[] fields = obj.getClass().getDeclaredFields();

    for(Field field : fields)
    {
        FieldType type = FieldUtils.getType(field); // FieldType is enum
        Object value = field.get(obj);
        Command command = commandMap.get(type);
        command.execute(value, this); // 'this' needed for calling processObjectRecursively()
    }
}

但是为此,我将需要创建一个接口和另外四个类。那么这种方法可行吗?还是设计过度?您可以建议其他任何更简单的方法来达到相同的效果吗?

But for this I will need to create one interface and four more classes. So is this approach okay or is it over-engineered? Can you suggest any other simpler approach to achieve the same effect?

推荐答案

我同意避免切换case语句总是更好。因此,创建命令映射即可。另一种更简单的方法是在枚举中添加process方法,以便每种枚举类型都知道如何处理数据。

I agree its always better to avoid switch case statement. So creating a command map would do. Another easier approach could be to add the process method inside your enum so that every enum type knows how to process the data.

这篇关于Java:在以下代码中使用命令模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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