Perhaps you could create a MessageFactory interface and its implementation:
public interface MessageFactory { Message createMessage(Map<String, Object> fields); Message createMessage(ByteBuffer buffer); } public class FirstMessageFactory implements MessageFactory { public Message createMessage(Map<String, Object> fields){ return new FirstMessage(fields); } public Message createMessage(ByteBuffer buffer){ return new FirstMessage(buffer); } }
next, the getFactoryFromId method in the same class as the methods above:
public static MessageFactory getMessageFactoryFromId(int uuid){ switch (uuid) { case FIRST_MESSAGE_ID: return new FirstMessageFactory(); ... default:
However, instead, it is better to create a Hashmap containing identifiers and factories, so you do not need to create a new Factory object each time you create a message. See also comment below .
and your methods:
public static Message fromMap(int uuid, Map<String, Object> fields) { getMessageFactoryFromId(uuid).createMessage(fields); } public static Message fromByteBuffer(int uuid, ByteBuffer buffer) { getMessageFactoryFromId(uuid).createMessage(buffer); }
Thus, you are using the Factory pattern, and there is no need to double the same switch statement.
(not tested this, maybe some compilation errors / typos)
Fortega
source share