Link to home
Create AccountLog in
Avatar of dpalyca755
dpalyca755

asked on

designing a runnable class that can do more than one task depending on the request

I want to design a runnable class which will have numerous methods which can act on a socket, but I want them to run in their own thread when invoked.

Is it possible to pass some sort of variable to the Run method that I pass when doing a
new thread(myRunnableClass).start(), which the run class can then use to know what to methods in particular to invoke?
Avatar of mccarl
mccarl
Flag of Australia image

I think in this situation (not knowing any more than what you posted above), I would probably just solve this problem by separating those various methods out into separate classes that each implement Runnable. Then you would just start a new Thread by passing the appropriate class object to the Thread constructor.

Remember that if there IS actually common code between those various handling methods (and that is the reason why you have them now all in the one class), you can put that common code in a base class, and have the various handling methods in their own, separate class and each of these classes "extend" the base class so that they can use the common code.
ASKER CERTIFIED SOLUTION
Avatar of Valeri
Valeri
Flag of Bulgaria image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
To avoid having loads of redundant code lying around in classes which don't need to implement every method, you may as well make all the controlling class methods static, and code for them as required in the each thread.
I think in this situation (not knowing any more than what you posted above), I would probably just solve this problem by separating those various methods out into separate classes that each implement Runnable. Then you would just start a new Thread by passing the appropriate class object to the Thread constructor.
Definitely. You certainly shouldn't have the selection logic in the Runnable itself.
You might use a factory pattern and place the selection logic in that. It would return the correct type of Runnable (or perhaps more clearly a sub-interface of Runnable) for the job
I'm agree and in the same time not agree with that. It depends what exactly this class represents. If it represents completely different tasks then using factory pattern is strongly recommended, but if it / for example / represents a car, and the different methods represent for example turnLeft(), turnRight(), stop() and go() then separating this actions in different "cars" is not good idea. The car is running and what it has to do has to be decided in run time.