java - How to call a method by the order of parameters in OOP? -
suppose have 4 classes a, b, c , container
and have following objects , how achieve following output adding code container class?
the first call "con" object should correspond the first parameter.
your answer appreciated !
a = new a(); b b = new b(); c c = new c(); container con = new container(a,b,c); con.calling(); con.calling(); con.calling(); the expected output :
calling calling b calling c public class { public void calla() { system.out.println("calling a"); } } public class b { public void callb() { system.out.println("calling b"); } } public class c { public void callc() { system.out.println("calling c"); } } public class container { public container(a a, b b, c c) { } public void calling(){ } }
looks similar iterator pattern/interface. here instead of calling() method next().
i can sketch you, like:
import java.util.arrays; import java.util.iterator; public class container implements iterator { private iterator<?> iter; public container(object ...values) { this.iter = arrays.aslist(values).iterator(); } @override public boolean hasnext() { return iter.hasnext(); } @override public object next() { return iter.next(); } } update after scrutiny consideration on question, i've decided expand answer. decision above iterator give rough idea. want more specific decision, , here java-8 method references:
1) container runnable instances:
import java.util.arrays; import java.util.iterator; public class container implements iterator { private iterator<runnable> iter; public container(runnable ...values) { this.iter = arrays.aslist(values).iterator(); } @override public boolean hasnext() { return iter.hasnext(); } @override public object next() { runnable next = iter.next(); next.run(); return next; } } and sample code test stuff:
container container = new container(new a()::calla, new b()::callb, new c()::callc); container.next(); container.next(); container.next(); in case not return next instance, invoke desired method.
Comments
Post a Comment