我希望在 Java 中的应用程序中可以使用/访问一些字符串值。不同的类(class)将需要它们。我想知道在整个应用程序中保留和访问这些值的最佳方法。
我知道的一种方法是在 Java 中使用 Enum 模式。我可以在其中将字符串值与每个枚举相关联,然后访问它。就像这里给出的那样。 Best way to create enum of strings?
其次是维护一类具有字符串值的常量。
什么是可能的最佳方法,以便遵循良好的设计并干净地访问所有内容。
我想知道。
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 值的额外开销。
最佳答案
第二个还好。但我不会创建一个类来包含所有不相关的常量。这无法扩展,而且不自然。相反,在常量所属的类中定义常量。例如:
public class Victim {
public static class DEFAULT_MALE_NAME = "John Doe";
public static class DEFAULT_FEMALE_NAME = "Jane Doe";
...
}
public class CreditCard {
public static final String DEFAULT_TYPE = "Visa";
...
}
编辑:
现在您提供了一些代码,看来您实际上应该定义一个或多个枚举,每个枚举都封装了应用于给定集合的 View 的概念。
关于java - 全局保存 String 类型值的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21648602/