Java Command Patterns | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java Command Patterns

Can anyone help me figure out how to implement command patterns in Java the way I'd like to. I'm trying to understand how they work but my eyes are starting to bleed. Basically what I'd like to do is have a few methods from a class assigned to a queue along with an argument for each method, and another class or method that will execute the few methods I have assigned. Forgive my pseudo code, but this is an example array[][] = { { class.method0(), var1 }, { class.method1(), var2 }, { class.method2(), var3 } }; for (int i: array) { execute(array[i][0], array[i][1]); } I hope what I'm asking here makes sense, I'm a little sleep deprived. Thanks!

10th Feb 2017, 10:14 PM
xum
xum - avatar
4 Answers
+ 3
I think I understand what you're getting at, but just to clarify. You want to: 1. Have a stored set of methods inside an array, alongside the arguments for the methods 2. Call those methods in sequence using an iterator statement Is this accurate?
10th Feb 2017, 11:02 PM
Sean Kudebeh
Sean Kudebeh - avatar
+ 3
I'm just going to throw a couple things out there and see if it helps -Try using two single arrays. -The For statement might be the problem, since the first parameter depends on the second. Since you're trying to avoid extra libraries try this. Define a method or class that takes integer numbers i.e. 0,1,2...etc Then within that "caller" method or class create conditionals that will test what number is input. Each number will correspond to a call to a different method (the method you actually want to execute) here's some psuedo-code the caller class/method: if(x==1) -> call class.method1 else if (x==2) -> call class.method2 Does this make sense? This way will avoid you having to explicitly use the call phrase within the array, which I think may cause problems. Additionally you need fewer arrays, just one to store your parameters. If this sounds totally crazy let me know I don't have a way to test this theory at the moment and I'm working mostly from memory
10th Feb 2017, 11:45 PM
Sean Kudebeh
Sean Kudebeh - avatar
+ 1
That's the basic gist of it. I did find an example similar to what I'd like to do that's closer than the remote control turning lights on/off analogy. http://javarevisited.blogspot.com/2016/05/command-design-pattern-in-java-example-code.html But i'm definitely interested in what your idea is, especially if it doesn't require additional libraries like the link I posted requires.
10th Feb 2017, 11:06 PM
xum
xum - avatar
0
what I ended up doing was using Callable and ExecutorService. I'm still working through it but I think I'm on the right track. thanks :)
11th Feb 2017, 5:33 AM
xum
xum - avatar