【发布时间】:2014-03-06 02:17:58
【问题描述】:
我希望一些 String 值对我来说是可用/可访问的,以通过 Java 处理应用程序。不同的班级将需要它们。我想知道在整个应用程序中保留和访问这些值的最佳方式。
我知道的一种方法是在 Java 中使用 Enum 模式。我可以将一个字符串值与每个枚举相关联,然后访问它。就像这里给出的一样。 Best way to create enum of strings?
二是维护一类带String值的常量。
什么是最好的方法,以便遵循良好的设计并干净地访问所有内容。
我想知道。
public class StringValues
{
public static final String ONE = "one";
public static final String TWO = "two";
}
我正在添加更多细节。
我将使用这些短名称字符串创建数据库查询。因此,在实例化数据库时我将在一个地方使用所有字符串并创建查询。
但是在创建查询之后,我需要一个特定类的字符串池的片段/部分,以便我可以为选定的类注册侦听器,而不是为池中的所有字符串。每个类都应该知道,它只需要 1-2 个字符串名称来注册运行时侦听器,而不是所有的字符串名称。
我一次需要所有字符串(在应用程序开始期间)然后我只需要 2 或 3 个或更多但不是全部。
这是让您了解我的确切设计问题的代码。
/**
*This class will be used to create Views in Database.
*/
class Views
{
public static final String BY_NAME = "byName";
public static final String BY_DATE = "byDate";
public static final String BY_GENDER = "byGender";
//For every String I am going to create Views in Couchbase.
}
/**
*This class knows to which Views it needs to listen to. If any change in its views occurs then
* it will take action. In case of byDate change it is intended to take an action.
*/
public class NewestMember
{
String[] viewsToQueryFor = {"byDate"};
//This class will call only these views and will register for them.
}
public class Male
{
String[] viewsToQueryFor = {"byName", "byGender"};
//This class will call only these views and will register for them.
}
public class Female
{
String[] viewsToQueryFor = {"byName", "byGender"};
//This class will call only these views and will register for them.
}
我不想这样做。为此,我需要在其他类中保留 String 值的额外开销。
【问题讨论】:
-
Id 取决于这些值是真的恒定还是可配置的。如果是第二种,最好将它们保存在 *.properties 文件中。
-
通常会将常量放在实际需要它们的类中。避免使用Constant interface antipattern。
-
@Hoosier 如果有那么多常量,那么您可能有一些设计问题 - 考虑将常量分组到描述其用途的
enum实例中,例如public enum CompassPoint、public enum Gender等。使用enum的一个优点是不能将Gender.MALE传递给需要CompassPoint的方法,因此该方法不需要检查无效输入。您还可以通过enum挂起更多数据。 -
从更新到问题,这似乎是一个经典的 XY 问题。根本不应该有常数。查询应该在 DAO 层中定义并在那里使用。它们应该不通过字符串连接构建,而是通过准备好的语句构建。
-
既然您提供了代码,如果我理解正确,我会说我坚持我最初的答案。视图名称适用于特定类型的数据。所以这些常量大概应该在PersonView中,而PersonView大概应该是一个枚举。在包含汽车或约会或其他任何东西的集合上应用
byGender视图是没有意义的。对于汽车,您将拥有一个包含 BY_COLOR 和 BY_MODEL 的 CarView 类或枚举。
标签: java design-patterns enums constants