2

这是一个有点令人困惑的问题,所以我会尽力问它。

假设我在特定代码块之前和之后有一堆代码。代码块周围的代码始终保持不变,但块内的代码可以更改。为简单起见,考虑环绕代码是一个双重嵌套的 for 循环:

for(int i = 0; i<width; i++){
    for(int i = 0; i<height; i++){

        // changing code block

    }
}

现在,我想告诉编译器将不同的代码位插入到我程序中不同实例的代码块中。我将如何去做这样的事情?

4

6 回答 6

5

如果我理解正确,您必须声明一个带有方法的接口并发送一个类的对象引用,该类实现包含要实现的逻辑的接口。基本代码示例:

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);
    }
}

在您当前的代码块中:

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);
        }
    }
    //...
}

现在您可以doXxx使用 的实现来调用Foo,例如Baror的实例Baz

doXxx(new Bar());
doXxx(new Baz());
于 2013-09-02T07:19:05.303 回答
3

我会使用外部服务来运行所需的代码,并使用 IOC(或任何你喜欢的)来为每个实例配置适当的服务。

private MyService myService;

for(int i = 0; i<width; i++){
    for(int i = 0; i<width; i++){

        myService.myMethod();

    }
}

并使用:

public interface MyService {
    public void myMethod();
}

public class MySimpleService {
    @Override
    public void myMethod() {
        // Do whatever...
    }
}

public class MyOtherService {
    @Override
    public void myMethod() {
        // Do whatever...
    }
}
于 2013-09-02T07:17:43.130 回答
2

其他语言可能会使用闭包来解决这个问题。对于 Java,您需要传递一个类的对象。

例如,您可能有一个名为 的函数Looper,它需要一个参数operation,您将使用此操作调用该函数。

要在 pre-java 8 中做到这一点,您可以做的是编写一个函数,该函数接受一个可以调用或等效的对象并执行您的操作。

(可能有小错误,见谅,写Java代码有一段时间了,希望思路清晰)

public interface Operation {
    public int performOperation(int a, int b);

}
...
public void Looper(Operation o, int a, int b){
    for(int i = 0; i<width; i++){
        for(int i = 0; i<width; i++){
             o.performOperation(a,b);
        }
    }


}



 //elsewhere

   Looper(new Operation{
       public int performOperation(int a, int b){
            return a + b;
       }

    }, 10,15);

这种模式见于map和函数式语言中的其他类似函数,foreach以及 C++ 中的一百万个其他函数。

于 2013-09-02T07:28:13.070 回答
0

您可以将if 条件switch 语句或任何条件语句放在块内。

执行单独的代码逻辑。

举个例子:

for(int i = 0; i<width; i++){
    for(int i = 0; i<width; i++){

        // changing code block
        if(codition1){
        //Execute block1 logic
        }
        else if(codition2)
        {
         //Execute block2 logic
        }


    }
}
于 2013-09-02T07:11:54.920 回答
0

你以错误的方式看待这个问题。如果您想简单地换出代码,请创建一个静态方法并调用它:

for(int i = 0; i<width; i++){
for(int i = 0; i<width; i++){

    m1();

}
}

for(int i = 0; i<width; i++){
for(int i = 0; i<width; i++){

    m2();

}
}

并使方法为:

static void m1(){
    //something
}

static void m2(){
    //something else
}
于 2013-09-02T07:13:29.797 回答
-1

将其更改为

    for(int i = 0; i<width; i++){
        for(int j = 0; j<width; j++){
于 2013-09-02T07:10:41.717 回答