Java - static factory method and switch statements -
i dealing set of message objects, each of has unique identifier corresponding them. each message can constructed either map, or bytebuffer (the messages binary, know how transfer , binary representation).
the current implementation constructing these messages follows:
public static message frommap(int uuid, map<string, object> fields) { switch (uuid) { case first_message_id: return new firstmessage(fields); . . . default: // error return null; } } public static message frombytebuffer(int uuid, bytebuffer buffer) { switch (uuid) { case first_message_id: return new firstmessage(buffer); . . . default: // error return null; } }
now, josh bloch's effective java talks item 1: consider static factory methods instead of constructors, , seems place pattern useful (clients don't directly access constructors of message subtypes; instead go through method). not fact have remember keep 2 switch statements updated (violates dry principle).
i appreciate insight best way accomplish this; we're not caching objects (each call frommap or frombytebuffer return new object), negates of benefit of using static factory method this. code strikes me wrong, love hear community's thoughts on whether valid way construct new objects, or if not better solution be.
maybe create interface messagefactory , implementations of it:
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, method getfactoryfromid in same class methods above:
public static messagefactory getmessagefactoryfromid(int uuid){ switch (uuid) { case first_message_id: return new firstmessagefactory(); ... default: // error return null; } }
however, instead of this, better create hashmap containing ids , factories, don't have create new factory object everytime creating message. see comment below.
and 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); }
this way, using factory pattern, , there no need have 2 times same switch statement.
(didn't test this, possibly compile-errors/typos)
Comments
Post a Comment