This is a bit of a confusing question so I'll do my best in asking it.
Say I have a bunch of code before and after a specific code block. The code surrounding the code block always stays the same but the code inside the block can change. For simplicity, consider that the surround code is a doubly nested for loop:
for(int i = 0; i<width; i++){
for(int i = 0; i<height; i++){
// changing code block
}
}
Now, I want to tell the compiler to insert different bits of code into the code block at different instances in my program. How would I go about doing something like this?
If I understand you right, you have to declare an interface with a method and send an object reference of a class that implements the interface that holds the logic to implement. Basic code example:
interface Foo {
public void doFoo(int i, int j);
}
class Bar implements Foo {
@Override
public void doFoo(int i, int j) {
System.out.println(i + j);
}
}
class Baz implements Foo {
@Override
public void doFoo(int i, int j) {
System.out.println(i - j);
}
}
In your current code block:
public void doXxx(Foo foo) {
//...
for(int i = 0; i<width; i++){
for(int j = 0; j<width; j++){
// changing code block
//solved using interfaces
foo.doFoo(i, j);
}
}
//...
}
Now you can call doXxx using an implementation of Foo, like an instance of Bar or Baz:
doXxx(new Bar());
doXxx(new Baz());
I would use external services to run the needed code, and use IOC (or whatever you like) in order to configure the proper service for each instance.
private MyService myService;
for(int i = 0; i<width; i++){
for(int i = 0; i<width; i++){
myService.myMethod();
}
}
And use:
public interface MyService {
public void myMethod();
}
public class MySimpleService {
@Override
public void myMethod() {
// Do whatever...
}
}
public class MyOtherService {
@Override
public void myMethod() {
// Do whatever...
}
}
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