使用枚举通用代码 [英] Making a code using enum generic

查看:123
本文介绍了使用枚举通用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,最初是为一个团队设计的,他们正在将一个枚举(其中存储任务列表)传给一个api。这个api然后将这个枚举的使用推送到很多其他类。



现在我有一个任务,这个代码需要被多个团队使用,他们可以自己传递以枚举形式的任务集。



鉴于目前的实现,我不认为支持多个团队完全修复代码是可行的,因为枚举不能扩展其他枚举。 / p>

有没有办法实现这个没有大的变化?

解决方案

但是,枚举可以实现接口,例如:

  public interface Task {
int getPriority(); //只是例如
//加上任何方法定义一个任务
}

public enum Team1Task实现Task {
Task1(1),
Task2 (3);
private final int priority;
private Team1Task(int priority){
this.priority = priority;
}
public int getPriority(){
return priority;
}
}

现在我们可以使用java通用功夫来指定通用参数绑定到适当的枚举:

  public class TaskProcessor< T extends Enum< T> &安培;任务> {
public void process(T task){
// do something with task
}
}

要使用它:

  TaskProcessor< Team1Task> p = new TaskProcessor< Team1Task>(); 
p.process(Team1Task.Open); //将只接受一个Team1Task实例






作为泛型的好奇心,您可以使用这个绑定来实现同样的事情:

  public class TaskProcessor< T extends Enum< ?扩展任务>> {

虽然我没有发现实际的差异,但我发现它缺乏清晰度和熟悉的模式交叉点上方。有关更多信息,请参阅此问题


I have a code which was initially designed for just a single team where they were passing an enum [which stores list of tasks] to an api. This api then progates the use of this enum to many other classes.

Now i have a task where this code needs to be used by multiple teams and they can pass there own set of tasks in form of enums.

Given the current implementation i dont think it is feasible to support multiple teams which completely overhauling the code because enum's cannot extend other enums.

Is there any way to implement this without massive changes?

解决方案

But... enums can implement interfaces, for example:

public interface Task {
    int getPriority(); // just for example
    // plus whatever methods define a task
}

public enum Team1Task implements Task {
    Task1(1),
    Task2(3);
    private final int priority;
    private Team1Task(int priority) {
        this.priority = priority;
    }
    public int getPriority() {
        return priority;
    }
}

Now we can employ java generic kung fu to specify a generic parameter bounded to a suitable enum:

public class TaskProcessor<T extends Enum<T> & Task> {
    public void process(T task) {
        // do something with task
    }
}

To use it:

TaskProcessor<Team1Task> p = new TaskProcessor<Team1Task>();
p.process(Team1Task.Open); // will only accept a Team1Task instance


FYI, as a curiosity of generics, you can alternatively use this bound to achieve the same thing:

public class TaskProcessor<T extends Enum<? extends Task>> {

Although I can find no practical difference in effect, I find it lacks the clarity and familiar pattern of the intersection bound above. For more on this see this question.

这篇关于使用枚举通用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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