2016년 4월 2일 토요일

디자인 패턴 - strategy pattern

같은포맷의  input 을 받고 output을 내놓는 여러 개의 알고리즘이 있다고 하자.

예를 들면, 이번 주 로또를 예측해내는 가지각색의 예측 알고리즘이 존재할 수 있다.

여러 종류의 알고리즘을 쉽게 갈아끼어서 돌려 보고 싶은 경우

strategy pattern이 매우 유용하다.

1. 일단 interface 를 만들어서 여러 알고리즘에서 공통되는 함수를 끄집어 내자.

interface PredictLotto {
    public int[] predict(int year, int month, int day, int nth);
    public void setPastData(List<LottoData> data);
}

2. 그럼 이 interface를 implements 한 각 알고리즘의 클래스를 만든다.

GeneticAlgorithmType1 implements PredictLotto {
    List<LottoData> data;
    public int[] predict(int year, int month, int day, int nth) { ///algorithm }
    public void setPastData(List<LottoData> data) { this.data = data; }
}

GeneticAlgorithmType2 implements PredictLotto {
    List<LottoData> data;
    public int[] predict(int year, int month, int day, int nth) { ///algorithm }
    public void setPastData(List<LottoData> data) { this.data = data; }
}

3. 사용하기 원하는 알고리즘 클래스를 인스턴스화해서 predict한다.

PredictLotto algo = new GeneticAlgorithmType1();
algo.predict();

댓글 없음:

댓글 쓰기