有没有任何理由重写Java 8中的枚举中的方法 [英] Is there any reason to override methods in enums in Java 8

查看:151
本文介绍了有没有任何理由重写Java 8中的枚举中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如这里所指出的,lambdas提供了一个相当优雅的方式为各个枚举值指定行为。

As pointed out here lambdas provide a quite elegant way of specifying behaviour for individual enum values.

在Java 8之前,我通常会将其实现为:

Before Java 8 I would normally have implemented this as:

enum Operator {
    TIMES {
        public int operate(int n1, int n2) {
            return n1 * n2;
        }
    },
    PLUS {
        public int operate(int n1, int n2) {
            return n1 + n2;
        }
    };

    public int operate(int n1, int n2) {
        throw new AssertionError();
    }            
}

现在我倾向于使用:

enum Operator {
    TIMES((n1, n2) -> n1 * n2),
    PLUS((n1, n2) -> n1 + n2);

    private final BinaryOperator<Integer> operation;

    private Operator(BinaryOperator<Integer> operation) {
        this.operation = operation;
    }

    public int operate(int n1, int n2) {
        return operation.apply(n1, n2);
    }
}

这看起来更加优雅。

我现在不能想到有理由替代特定枚举值的方法。所以我的问题是,现在有没有什么好的理由可以在一个枚举中使用方法覆盖,还是应该有一个功能界面?

I cannot think of a reason to override methods for a specific enum value now. So my question is, are there any good reasons to use method overrides in an enum now or should a functional interface always be preferred?

推荐答案

如果您查看这个答案,它总结了在这个枚举场景中使用lambda表达式的优点,您可能会注意到这些优势都在Java 8之前的版本中消失。它不像旧的专门的枚举变体更可读,也不会提高性能。此外,在Java 8之前,接口BinaryOperator 不存在,所以这是另一个类,你需要添加到你的代码库来遵循这种方法。

If you look at this answer which summarizes the advantages of using lambda expression in this enum scenario you might notice that these advantages all disappear in the pre-Java 8 variant. It’s neither more readable than the old specialized enum variant nor does it improve the performance. Further, the interface BinaryOperator doesn’t exist before Java 8 so it’s another class you would need to add to your codebase to follow this approach.

在Java 8之前的代码中使用这种授权方法的主要原因是,如果您打算尽快切换到Java 8,可以简化迁移。

The main reason to use this delegation approach in pre-Java 8 code would be to ease the migration if you plan to switch to Java 8 soon.

更新到您更新的问题:

如果您主要关注Java 8用例,我建议始终当所有枚举案例具有不同的行为时,使用委托方法,该行为仍然遵循类似的模式,可以从使用lambda表达式中受益,因为在实例中使用像例子

If you mainly focus on the Java 8 use case, I would recommend to always use the delegation approach when all enum cases have a different behavior which still follows a similar pattern which can benefit from using lambda expressions, as it’s the case when implementing operators like in your example.

一个反例子将是一个枚举,其中大多数共享一个常见的行为,将被覆盖只有一个或几个例子。例如:

A counter-example would be an enum where most of them share a common behavior that will be overridden for one or a few cases only. E.g.:

enum Tokens {
    FOO, BAR, BAZ, AND, A, LOT, MORE // etc …

    /** Special Token End-Of-File */
    EOF {
        @Override
        public boolean matches(String input, int pos) {
            return input.length()==pos;
        }
    };

    // all ordinary tokens have the same behavior
    public boolean matches(String input, int pos) {
        return input.length()-pos >= name().length()
          && input.regionMatches(pos, name(), 0, name().length());
    }
}

这篇关于有没有任何理由重写Java 8中的枚举中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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