2013-04-25 1 views
1

메쏘드는 어떤 결과를 리턴하고 그것을 빌드하기 위해 "시도"를합니다. 성공한 첫 번째 시도가 반환되어야합니다. 그들 중 누구도 예외가 발생한다 성공하지 않는 경우 :오류/예외가 누적 된 디자인 패턴

class Calculator { 
    public String calculate() throws Exception { 
    // how do design it? 
    } 
    private String attempt1() throws Exception { 
    // try to calculate and throw if fails 
    } 
    private String attempt2() throws Exception { 
    // try to calculate and throw if fails 
    } 
    private String attempt3() throws Exception { 
    // try to calculate and throw if fails 
    } 
} 

을이 calculate에 의해 throw 예외가 개인 메소드에 의해 슬로우 다른 모든 예외의 스택 추적을 보존해야한다고 언급하는 것이 중요합니다. 확장 성 및 유지 보수성을 염두에두고 calculate() 메서드를 어떻게 설계 하시겠습니까?

답변

2

복합 및 명령을 사용합니다.

interface CalculateCommand { 
    public void calculate(CalculateContext context); 
} 

이제 각 시도에 대한 구현을 만듭니다. 다음은 CompositeCommand을 만들

는 - 여기 개요는 각 명령의 구현에 대한 검증 드디어

CalculateCommand allCommands = new CompositeCalculateCommand(someListOfCommands); 
allCommands.calculate(someContextThatYouDefine); 
// results now on context. 

주처럼 사용

public class CompositeCalculateCommand implements CalculateCommand { 

    CompositeCalculateCommand(List<CompositeCommand> commands) { 
     this.commands = commands; // define this as a field 
    } 

    public void calculate(CommandContext context) { 
     for (CalculateCommand command : commands) { 
       try { 
        command.calculate(context); 
       } catch(RuntimeException e) { 
        this.exceptions.add(e) // initialize a list to hold exceptions 
       } 
       if (context.hasResult) return; // break 
     } 
     // throw here. You didn't success since you never saw a success in your context. You have a list of all exceptions. 
    } 

} 

을 (당신이 빈칸을 채워해야합니다) 자사의 소유하고 있기 때문에 이것은 매우 유지할 수 있습니다. 계산을 추가해야하는 경우 새 유형 CalculateCommand을 정의하기 만하면 확장 가능합니다. 의존성 주입과도 잘 작동합니다. 참고 CommandContext 객체를 정의하여 다른 명령이 다른 유형의 항목 (컨텍스트에 넣음)을 사용할 수 있도록합니다.