I am working with a communication standard (over which I have no control) that defines data items to be sent/received in various packets.
Each item is defined by a custom type, and type-dependent information. These items will rarely change. I'd like to be able to limit the scope of item constructors to one place, and define all items there once as public static (similar to an enum).
Currently, I have an enum for the types, and a class for the items.
enum Type {TYPE_A, TYPE_B, ...}
public class Item {
public static Item ITEM_1 = new Item(TYPE_A, someNumber);
public static Item ITEM_2 = new Item(TYPE_B, someNumber, someMap);
public static Item ITEM_3 = new Item(TYPE_A, someNumber);
...
// Constructor for type A
private Item(Type type, int param1) {...}
// Constructor for type B
private Item(Type type, int param1, Map param2) {...}
...
// Type-dependent methods
public String decode(byte[] data) {
switch(this.type) {
case TYPE_A:
...
}
case TYPE_B:
...
}
...
}
}
This has become unmanageable, and I am looking for a better pattern / structure.
I could have an abstract Item class, and subclass for each type. With this setup, I don't know how I could define all the items in one place without making all the constructors public.
enums? Enums can have fields, methods and constructors.Itemclass anEnumis a good suggestion. But this does not fully solve the problem. I'll still have 20+ constructors... one for each enum constant.