gpt4 book ai didi

java - 使用枚举来保存对象常量

转载 作者:搜寻专家 更新时间:2023-11-01 01:50:30 24 4
gpt4 key购买 nike

所以我最近学到了很多东西,所以我要回去重构我以前上过的类(class)的家庭作业,以使用良好的实践来实现它们。一项作业让我们实现了一个 Planner 对象,其中包含一组 Course 对象。我正在尝试创建一些类(class)常量,这样我就可以访问一些受欢迎的类(class),而不必每次都创建全新的对象,这样我就可以轻松访问它们而无需通过类(class)构建过程。我对枚举没有太多经验,而且我似乎找不到任何关于如何实际使用枚举来存储对象常量的信息。我最初想让它们成为 Course 类中的常量,但 Effective Java 坚持在这种情况下应该使用枚举。我的实现是否有意义?我应该如何制作包含 Course 常量的枚举,以便我可以实际检索它们?我使用 Builder 方法创建类(class)。

public enum Courses {
CSE_114, CSE_214, CSE_219, CSE_215;

private final static Course CSE_114_COURSE = new Course
.Builder("Computer Science 1", "Paul Fodor", 114)
.section((byte)1).department("CSE").build();

private static final Course CSE_214_COURSE = new Course
.Builder("Data Structures", "Ahmad Esmaili", 214)
.section((byte)1).department("CSE").build();

private static final Course CSE_219_COURSE = new Course
.Builder("Software Development", "Richard McKenna", 219)
.section((byte)1).department("CSE").build();

private static final Course CSE_215_COURSE = new Course
.Builder("Foundations of CS", "Paul Fodor", 215)
.section((byte)1).department("CSE").build();

public static Course get(Courses c) {
switch(c) {
case CSE_114: return CSE_114_COURSE;
case CSE_214: return CSE_214_COURSE;
case CSE_219: return CSE_219_COURSE;
case CSE_215: return CSE_215_COURSE;
default: throw new IllegalArgumentException("Course does not exist.");
}
}
}

最佳答案

您实际上可以像对待对象一样对待枚举:

public enum Course {
CSE_114("Computer Science 1", "Paul Fodor");

public final String room;
public final String lecturer;

private Course(room, lecturer) {
this.room = room;
this.lecturer = lecturer;
}
}

因为它是枚举,所以所有值都必须在编译时已知。这是由 Java 语言强制执行的,它要求枚举构造函数是私有(private)的。

虽然这适用于您的情况,但我不推荐它 - 事实上,我根本不推荐使用枚举。枚举表示一组固定的已知值。如果您想在运行时创建更多类(class),那么枚举是不完整的,这与枚举的定义相矛盾。

相反,我建议您使用 CourseManager。创建一个类,其中包含所有已知类(class)的集合。然后,当您需要类(class)时,您可以按名称请求。

Course cs114 = courses.get("CS 114");

您还可以更进一步,通过从文件实例化 CourseManager,该文件包含 JSON 等基本格式的类(class)列表。

关于java - 使用枚举来保存对象常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com