我想實現一個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 = "123456789";
String field2 = "12345" + FNC1;
String id2 = "00";
String field3 = "123456789";
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個標識符。所以,我認爲這是時間和記憶的一種滋味。我搜索解析器的「懶惰inizialitation」設計,但我還沒有找到與我的問題相對應的東西。有更好的設計嗎?或者我的擔心是沒有用的。
謝謝
那麼「存儲」映射中的值實際上會被讀取和返回嗎? 'search'方法是否只返回'INSTANCE'? – 2014-09-02 14:37:15
使用地圖存儲解析器對象似乎是一個好主意,我只有兩個Parser對象的對象實例。但它是否安全?正如馬特所說,我沒有看到如何從搜索方法中獲得標識符。 – user1151816 2014-09-02 15:04:46
請參閱我的文章的編輯。我澄清了搜索功能中的邏輯。因此,如果代碼包含在地圖中,則返回所需的內容,否則將其初始化。對於線程安全來說,鎖現在保護對hashmap的訪問。 – Esquive 2014-09-02 15:18:35