와챠의 우당탕탕 코딩 일기장
[JAVA 디자인 패턴] - 6, Strategy 패턴 본문
반응형
Strategy Pattern
Strategy 패턴은 알고리즘을 쉽게 교체할 수 있는 패턴이다.
예제로는 플레이어가 레벨 1일 때는 쉬운 공격을 하고,
레벨 2일때는 어려운 공격을 하는 코드를 짜 봤다.

- Strategy 인터페이스 = 레벨에 따라 다른 공격을 구현하게 함
- Level 1 클래스 = 레벨 1의 공격인 쉬운 알고리즘 구현
- Level 2 클래스 = 레벨 2의 공격인 어려운 알고리즘 구현
- (※원래는 attack에 알고리즘이 들어가야 하는데 간단하게 표현하고자 생략)
- Player 클래스 = 플레이어를 나타내는 클래스
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package StrategyPattern; | |
// 레벨 1 | |
public class Level1 implements Strategy { | |
@Override | |
public void attact() { // 레벨 1 공격 | |
// 레벨 1 알고리즘 | |
System.out.println("옷---->"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package StrategyPattern; | |
// 레벨 2 | |
public class Level2 implements Strategy { | |
@Override | |
public void attact() { // 레벨 2 공격 | |
// 레벨 2 알고리즘 | |
System.out.println("옷--------------->"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package StrategyPattern; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
public class Main { | |
public static void main(String[] args) throws IOException { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
Player player = new Player("minWachya", new Level1()); // 레벨 1 플레이어 생성 | |
String str = ""; | |
System.out.println("게임을 시작합니다."); | |
while(true) { | |
// 입력받기 | |
System.out.print(player.getName()); | |
str = br.readLine(); | |
if (str.equals("종료")) break; // "종료" 입력하면 게임 끝 | |
if (str.equals("얍")) { // "얍" 입력 시 공격 | |
player.attack(); // 공격, 경험치 ++ | |
if(player.getAttackNum() == 3) { // 경첨치가 3이면(공격을 3번 하면) | |
System.out.println("~~~Level up!!!~~~");// 레벨업 | |
player.levelUp(new Level2()); // 레벨 2가 됨 | |
} | |
} | |
} | |
System.out.println("종료되었습니다."); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package StrategyPattern; | |
// 플레이어 | |
public class Player { | |
private String name; // 이름 | |
private Strategy strategy; // 공격 스킬(레벨에 따라 달라짐) | |
private int attackNum = 0; // 경험치(공격 횟수) | |
public Player(String name, Strategy strategy) { | |
this.name = name; | |
this.strategy = strategy; | |
} | |
public void attack() { // 공격 스킬은 Strategy한테 위임 | |
strategy.attact(); // 공격 | |
attackNum++; // 경험치++ | |
} | |
public String getName() { // 이름 리턴 | |
return "[" + name + "]:"; | |
} | |
public int getAttackNum() { // 경첨치 리턴 | |
return attackNum; | |
} | |
public void levelUp(Strategy strategy) { // 알고리즘 바꾸기(레벨업) | |
this.strategy = strategy; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package StrategyPattern; | |
// 레벨에 따라 다른 공격을 구현하게 하는 인터페이스 | |
public interface Strategy { | |
public abstract void attact(); // 공격하기 | |
} |

장점
Player 클래스에 구체적인 Strategy 클래스(Level 1, Level 2)는 보이지 않는다.
Strategy의 일이 필요할 때엔 필드인 strategy에게 위임(◇) 하기 때문에
알고리즘을 유연하게 교체할 수 있다.
활용 :
- 빠른 알고리즘을 찾기 위해 알고리즘마다 시간을 재기
- 각 프로그램에 맞는 알고리즘으로 교체하기
JAVA 언어로 배우는 디자인 패턴 입문(p 179~191) 참고
반응형
'코딩 일기장 > JAVA 디자인 패턴' 카테고리의 다른 글
[JAVA 디자인 패턴] - 7, Composite 패턴 (0) | 2020.11.09 |
---|---|
[JAVA 디자인 패턴] - 5, Singleton 패턴 (0) | 2020.10.02 |
[JAVA 디자인 패턴] - 4, Factory Method 패턴 (0) | 2020.10.02 |
[JAVA 디자인 패턴] - 3, Template Method 패턴 (0) | 2020.09.22 |
[JAVA 디자인 패턴] - 2, Adapter 패턴 (0) | 2020.09.16 |