7

전략 패턴을 구현하는 여러 Java 클래스가 있습니다. 각 클래스에는 다양한 유형의 변수 번호 매개 변수가 있습니다.매개 변수화 된 전략 패턴

interface Strategy { 
    public data execute(data); 
} 

class StrategyA implements Strategy { 
    public data execute(data); 
} 

class StrategyB implements Strategy { 
     public StrategyB(int paramA, int paramB); 
     public data execute(data); 
} 

class StrategyC implements Strategy { 
     public StrategyC(int paramA, String paramB, double paramC); 
     public data execute(data); 
} 

이제 사용자가 어떤 종류의 UI에서 매개 변수를 입력 할 수있게하려고합니다. UI는 런타임에 선택되어야합니다. 즉, 전략은 그것과 독립적이어야합니다. 매개 변수 대화 상자는 모 놀리식이 아니어야하며 각 전략 및 UI (예 : 콘솔 또는 스윙)별로 다르게 보이게 할 수 있어야합니다.

이 문제를 어떻게 해결하겠습니까?

답변

4

하나의 가능성은해야 할 일이 빌더 디자인 패턴과 비슷한 함께 :

은 해당 빌더 (하나 이상)이 있어야 모든 전략 유형하십시오. 빌더는 모든 빌더를 메소드 인수로 수신하는 일반 빌더처럼 작동하지 않습니다. 대신 관련 입력을받을 때까지 블록이어야합니다. 일부 빌더는 스윙 대화 상자를 표시하고 대기하고, 다른 사용자는 콘솔에 인쇄하여 입력 대기, 다른 사용자는 파일에서 읽을 수 있습니다. 빌더가 모든 입력을 수신하면 전략 인스턴스를 작성하여 리턴 할 수 있습니다.

이렇게하면 전략에서 데이터 검색 논리를 분리 할 수 ​​있습니다. 또 다른 이점은 모든 빌더의 일반 인터페이스를 가질 수 있으므로 특정 빌더를 선택하면 동일한 코드로 조작 할 수 있다는 것입니다.

+0

+1 즉, 빌더 자체가 전략이 될 것입니다. 좋은. –

1

이 문제의 해결책은 주로 어떤 전략이 현재 전략인지 결정하는 것에 달려 있습니다. 간단하게 UI가 모든 전략에서 동일하다고 가정합니다.

실제로 빌더 클래스 또는 팩토리 메소드를 작성하게됩니다. 이 라인을 따라 뭔가 : 당신이 진짜 공상 싶은 경우

interface StrategyPicker { 
    public Strategy getStrategy(); 
} 

// Most likely used in the JFrame it is added to 
class StrategyPickerUI extends JPanel implements StrategyPicker { 
    // initialize the panel with all the widgets 
    // and implement the getStrategy method. the getStrategy 
    // method should be called after the input is done in this 
    // panel (such as clicking an Ok or Apply button) 
} 

// You can also make one for the console app 
class StrategyPickerSimple implements StrategyPicker { 
    // ... 
} 

당신이 그것을 자신의 클래스로 만드는 행위를 제거하는 간단한 팩토리 클래스를 만들 : 당신은 UI를 유지하려면

public class StrategyFactory() { 
    public static Strategy createStrategyFromParameters(StrategyParams sp) { 
     // creates the Strategy object... doesn't need to be public static 
     // and if it isn't, it will help making unit tests easier 
    } 

    // This nested class could be split up to StrategyAParams, 
    // StrategyBParams, StrategyCParams 
    public class StrategyParams { 
     data paramA; 
     int paramB_A; 
     int paramB_B; 
     int paramC_A; 
     String paramC_B; 
     float paramC_C; 
    } 
} 

// in StrategyPickerUI class 
    public getStrategy() { 
     StrategyParams sp = new StrategyParams(); 
     sp.paramB_A = myJTextFieldParamB_A.getText(); 
      // and so on... 
     return StrategyFactory.createStrategyFromParameters(sp); 
    } 

모 놀리식이 아닌 경우, 책임을 자신의 개체로 나눕니다. 희망이 도움이됩니다.

0

매개 변수 클래스에 간단한 객체 (Numbers, Boolean, Date, String)가 포함되어 있으면 런타임에 인터페이스를 생성 할 수 있습니다.

이 구성 객체 및 매개 변수

의 수집을위한 UI를 생성이 강력한 UI 생성기의 Metawidget에 대한보고는 더 어려울 것이다.