我想实现一个 EAN128 条形码解析器。简而言之,EAN128 条码由一个或多个字段组成,每个字段由一个字符串标识符和一个值组成。有一百个不同的标识符,每个值都有固定或可变长度(数字或字母数字),具体取决于标识符。可变长度值以名为 FNC1 的特殊字符结尾。
我想从条形码中获取所有标识符及其值。
我的设计基于一个枚举,每个代码标识符都有一个字段。
public enum IDENT_EAN128 {
// Identifier 8003 that has a value composed by 14 numeric chars and 1 to 20 alphanumeric chars
IDENT_8003 ("8003", FixedParser(14, NUMERIC), VariableParser(20, ALPHANUMERIC)),
IDENT_00 ("00", FixedParser(18, NUMERIC)),
.... // hundred identifiers
private IDENT_EAN128 (String code, Parser... parsers ) {
...
}
public static IDENT_EAN128 search (String code) {
// loop IDENT_EAN128.values() to search code identifier
}
}
public class Main {
public static void test () {
String id1 = "8003";
String field1 = "12345678901234";
String field2 = "12345" + FNC1;
String id2 = "00";
String field3 = "123456789012345678";
String barcode = id1 + field1 + field2 + id2 + field3;
for (int posBarcode; posBarcode < barcode.length(); posBarcode++) { // loop chars of barcode
char[] buffer ...
IDENT_EAN128 idEAN = IDENT_EAN128.search(buffer)
if (idEAN != null) {
// loop Parsers for get identifier value
// move posBarcode to the first barcode position of next identifier
}
....
}
}
}
解析器返回标识符值,验证其长度并验证该值是否具有正确的字符类型(数字或字母数字)。 这种设计的问题在于,当第一次被调用时,它会创建数百个新对象(每个标识符及其解析器)。大多数时候条形码只有 3 或 4 个标识符。所以,我认为这是浪费时间和内存。我搜索了解析器的“惰性初始化”设计,但没有找到与我的问题相对应的内容。有更好的设计吗?否则我的担心是徒劳的。
谢谢
最佳答案
我认为您可以保留枚举方法。但是利用枚举单例功能。 我的意思是你只有 INSTANCE 枚举值。在您的枚举中,您保留一个以代码为键的 HashMap 。由于您的方法使用代码作为输入。看这个:
public enum IDENT_EAN128_CACHE {
INSTANCE;
private static final Map<String, ParserStore> storage = new HashMap<>();
public synchronized IDENT_EAN128 search (String code) {
// If the code is already in the map return the needed values
// Else lazy initialize the hashmap entries if the requested entry is not contained and return it.
return 'the value you should return';
}
}
然后您就可以像这样访问这些功能:
IDENT_EAN128.INSTANCE.search("some code");
编辑:
使用这种设计,如果您想延迟初始化 IDENT_EAN128,则不能将其保留为枚举。它应该是一个由我提供代码的“枚举缓存”初始化的对象。
编辑 2:Mike Strobel 在评论中建议的代码修改。
关于java - 具有很多字段的枚举设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25625702/