Consider a problem, in which I'm developing a tree like Collection.
One of the main functionality of my Collection is to trace all the stored items one by one and then call a given function for each item until a given criteria has been met (lazy Collection).
So the function should have the following signatures:
void Trace(function func, criteria crit)
{
item i = firstItem();
while (i != endItem())
{
i = nextItem();
func(i);
if (crit(i))
return;
}
}
in C++
function pointers can be used for func
and crit
.
in C#
, yield
keyword is exactly the solution to this problem, I believe.
How can I get the same thing in Java?
In Java, you would pass references to objects of classes that implement applicable functions, or use Commons Collections instead:
Predicate
implementations for the crit
part.Closure
implementations for the func
part.For example:
Closure c = new Closure() {
public void execute(Object obj) {
...
}
};
Predicate p = new Predicate() {
public boolean evaluate(Object obj) {
...
}
}
Trace(c, p);
What you're looking for here is the Strategy design pattern.
The goal of this pattern to to abstract the implementation of an algorithm into a Strategy object. Here, your algorithms are the func
and crit
functions that you're looking to pass in.
So, you'd have an interface called something like TraceStrategy
. You'd then pass implementations of this interface in to your collection. Your code would then look something like
void Trace(TraceStrategy traceStrategy)
{
item i = firstItem();
while (i != endItem())
{
i = nextItem();
traceStrategy.func(i);
if (traceStrategy.crit(i))
return;
}
}
and
interface TraceStrategy {
public boolean crit(item i);
public void func(item i);
}
You'd probably want to make this generic, so that you weren't tied to item
... but you get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With