2013-03-16 4 views
-1

코어 Java 응용 프로그램의 중첩 된 조건 인 경우 중첩 된 문제가 발생합니다. 코드 요약은 다음과 같습니다. ... 우리는 조건을 거의 20 개 중첩 할 수 있습니다. 이 방법을 최적화하는 방법을 알려줄 수 있습니까? 코드 조각?조건이 중첩 된 경우

Java 애플리케이션의 디자인 관점에서 볼 때 java.i의 조건이 20 개의 중첩 된 조건을 가질 수있는 경우 중첩되지 않도록하는 더 좋은 방법은 무엇입니까?

자바 자바 버전 1.6

String condition = getCondition(); 
if (condition.equals(add)) { // add operation 
    add(); 
    if (condition.equals(sub)) {// sub operation 
     sub(); 
     if (condition.equals(div)) { //div operation 
      div(); 
      if (condition.equals(cos)) { // cos operation 
       cos(); 
      } 
     } 
    } 
} 

편집의 솔루션을 도와주세요 : 나는 수 많은 수학 연산 20이 더 큰 많은입니다 then.20 작업 작업을 전환 할 것이라고 밝혔습니다.

답변

1

주 패턴 :이 같은

public enum Operation { 
ADD { 
    int execute(int a, int b) { 
     return a + b; 
    } 
}, 
SUB { 
    int execute(int a, int b) { 
     return a - b; 
    } 
}, 
MUL { 
    @Override 
    int execute(int a, int b) { 
     return a * b; 
    } 
}, 
DIV { 
    @Override 
    int execute(int a, int b) { 
     return a/b; 
    } 
}; 

abstract int execute(int a, int b); 

public static void main(String[] args) { 
    Operation oper = getOperation(); 
    oper.execute(3, 4); 
} 

private static Operation getOperation() { 
    return Operation.MUL; 
} 

}

가 :

public static void main(String[] args) { 
    String operation = user set it 
    Operation oper = getOperation(operation); 
    oper.execute(3, 4); 
} 

private static Operation getOperation(String operation) { 
    return Operation.valueOf(operation.toUpperCase()); 
} 

주의 다른-경우하는 대신이 같은 조건 경우 사용해야

1

대신 switch 문을 사용하십시오. 결정을 많이 할 때 이것을 사용하십시오.

Stringswitch 문에 사용하려는 경우에만 JDK 7에서 발생할 수 있습니다. 이전 버전 enum에서 도움이 될 수 있습니다.

+0

우리가 관련된 유형이나 OP가 사용하고있는 Java 버전을 알지 못해 불행합니다. 이것은 적절할 수도 적절하지 않을 수도 있습니다 - 답안에서이 점에 대해 명확한 가치가 있습니다. –

+0

@ JonSkeet, 사용 된 버전은 Java 1.6 – Deepak

0

코드에 따르면 항상 다음 줄을 실행하려면 condition.equals(add)을 만족해야합니다. 그물 선의 조건에 따라 다음 조건을 만족시키지 않습니다. 다음 줄로 들어가면? 당신은 switch을 사용할 수 있습니다

는 문자열 조건의 번호를 확인하십시오.

String condition = getCondition();  
    switch(condition) { 
     case add: 
      add(); 
      break; 
     case sub: 
      sub(); 
      break; 
     // etc... 
    } 

사이드 노트 : Java7에서 사용할 수있는 문자열을 켭니다.

String condition = getCondition();  
if(condition.equals(add)) 
    add(); 
else if(condition.equals(sub)) 
    sub(); 
else if(condition.equals(div)) 
    div(); 
else if(condition.equals(cos)) 
    cos(); 
2

그 Operation.valueOf 일 수 있습니다 NullPointerException - operation가 null의 경우, IllegalArgumentException - 조작이 enum의 어떤 것도 아닌 경우 enum

1

if 문장을 중첩 할 필요가없는 경우, 커멘드 패턴을 사용할 수 있습니다.

먼저 matcher와 명령 간의 매핑을 설정하십시오. 명령은 Runnable, Callable 또는 my example Command와 같은 공통 호출 인터페이스를 준수합니다. 이 예제는 래퍼를 동적으로 생성하고 정적 또는 비 정적 클래스를 사용하는 방법을 보여줍니다. 나중에 실제로 명령을 추가하고 제거 할 수 있기 때문에 실제 명령을 알지 못하는 경우이 패턴이 실용적입니다.

public class CommandExample { 

    private interface Command { 
     public void execute(); 
    } 

    private Map<String, Command> commands = new HashMap<>(); 

    private void setUp() { 
     commands.put("add", new Command() { 
      public void execute() { 
       add(); 
      } 
     }); 
     commands.put("sub", new Sub()); 
     commands.put("arg", new Argument("the argument")); 
    } 

    private void add() { 
     System.out.println("Add called"); 
    } 

    private static class Sub implements Command { 
     @Override 
     public void execute() { 
      System.out.println("Sub called"); 
     } 
    } 

    private class Argument implements Command { 

     private final String arg; 

     public Argument(String arg) { 
      this.arg = arg; 
     } 

     @Override 
     public void execute() { 
      System.out.println("Argument called with arg " + arg 
        + " and access to outer class " + CommandExample.this); 
     } 
    } 

    private void execute(String... names) { 
     for (String name : names) { 
      Command command = commands.get(name); 
      if (command != null) { 
       command.execute(); 
      } else { 
       System.err.println("Command '" + name 
         + "' is not known. Only know " + commands.keySet()); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     CommandExample commandExample = new CommandExample(); 
     commandExample.setUp(); 
     commandExample.execute("add", "sub", "arg", "unknown"); 
    } 
} 
+0

입니다. 제 시스템에서 실행될 수 있도록 작업 예제를 제공하거나 www.ideone.com에 Java 섹션 – Deepak

+0

@Deepak으로 게시 할 수 있습니다. 당신이 준 예제 (당신의 메소드는 인자를 취하지 않는다). 그러나, 나는 당신이 필요로하는 것을 정확히 알지 못하는 완전한 예를 만들려고 노력할 것이다. –

+0

@ Roger.but 여기에 숫자를 추가하지 않습니다. 단순히 add(), sub() 메소드를 호출하는 것입니다. – Deepak

1

여기에는 열거 형을 사용하는 방법에 대한 예가 있습니다.먼저

enum MathOperations{ 
    ADD, SUB, DIV, COS; 
} 

는 그런 다음 getCondition()MathOperations 인 요소를 반환합니다 경우에만 작동합니다 물론이

MathOperations m = MathOperations.valueOf(getCondition().toUpperCase); 
switch(m) { 
    case ADD: add(); break; 
    case SUB: sub(); break; 
    //and so on... 
} 

처럼 사용할 수있는 열거 만듭니다. 그렇지 않으면 IllegalArgumentException이됩니다.


Strategy pattern을 사용해 볼 수도 있습니다.

1

add, sub, div, cos ...을 정렬 된 목록/배열에 넣을 수 있습니다. 그런 다음 for 루프를 사용하여 목록을 반복합니다. 적절한 방법을 호출하려면 break 연산자와 reflection을 사용하십시오.

final String[] OPERATION_LIST = { "add", "sub", "div", "cos" }; 
String condition = getCondition(); 
for (String op : OPERATION_LIST) { 
    if (condition.equals(op)) 
     getClass().getMethod(op).invoke(this); 
    else 
     break; 
} 

for 루프는 중첩 if 제표에 동일합니다. 단점은 다른 수학 방법이 public이어야합니다. 그렇지 않다면 Accessing Private Methods과 같은 것이 필요합니다.

메모 : 계산기를 만들면 (아마도?) 아마도 Reverse Polish notation이 좋습니다.