java - Selecting a class dynamically at runtime -
im trying come solution class processes "message" selected @ runtime depending on message type. know can use
if msg_type = "a" msgaprocessor.execute(message); else if msg_type = "b" msgbprocessoror = execute(message); .... .... ....
i dont want use above approach dont want code know message types processing. want able in future add new message processor new message type. solution thinking of @ moment follows
there 3 message processors @ moment
msgaprocessor msgbprocessor msgbprocessor
all 3 classes have method called execute process message in own way. have created interface called msgprocessor , added execute() method in interface.
now having difficulty in knowing message processor caller should call without having check message type. example, cant this
msgprocessor proc = new msgaprocessor() proc.execute()
the above stil required in if statement needs called after finding out message type. avoid instantiating using implementation class type.
is there better way of achieving same?
i want able call msgprocessor.execute interface , have runtime environment know implementation class call based on message type.
- have interface processor has method execute(). 3 msgprocessors implement this.
- have separate class processorcontrol has submit(string message) method. whenever new message comes, processorcontrol.submit(message)
- now processorcontrol has method addprocessor(proccesor proc, string type) adds processors hashtable type key. hence each processor assigned type.
- in submit method, hashtable.get(type).execute(proc)
this simple command pattern.
Comments
Post a Comment