행위를 클래스로 캡슐화하여 행위를 자유롭게 바꿀 수 있도록 하는 행위 패턴
- Strategy : 알고리즘에 대한 공통 연산을 정의한 인터페이스
- ConcreteStrategy : Strategy 인터페이스 구현체로, 실제 알고리즘 구현
- Context : 실제 알고리즘을 사용하는 클래스
게임 캐릭터의 직업 전사를 구현한다고 가정해보자. Strategy Pattern을 이용하면 대검, 도끼 등의 무기변경을 주입하여 유연하게 공격할 수 있다.
[WeaponBehavior.java]
// Strategy
public interface WeaponBehavior {
void attack();
String getWeaponType();
}
// ConcreteStrategy
class Sword implements WeaponBehavior {
String type = "대검";
@Override
public void attack() {
System.out.println("칼로 공격!");
}
@Override
public String getWeaponType() {
return type;
}
}
class Axe implements WeaponBehavior {
String type = "도끼";
@Override
public void attack() {
System.out.println("도끼로 공격!");
}
@Override
public String getWeaponType() {
return type;
}
}
[MoveBehavior.java]
// Strategy
public interface MoveBehavior {
void move();
}
// ConcreteStrategy
class WalkBehavior implements MoveBehavior{
@Override
public void move() {
System.out.println("걸어서 이동");
}
}
class RunBehavior implements MoveBehavior {
@Override
public void move() {
System.out.println("달려서 이동");
}
}
[Character.java] / Super Class
public abstract class Character {
WeaponBehavior weaponBehavior;
MoveBehavior moveBehavior;
public void performAttack() { // 기본 공격 설정
this.weaponBehavior.attack();
}
public void performMove() { // 기본 이동 방법 설정
this.moveBehavior.move();
}
public void setWeapon(WeaponBehavior weapon) { // 무기 교체
this.weaponBehavior = weapon;
}
public void setMoveBehavior(MoveBehavior moveBehavior) { // 이동 방법 변경
this.moveBehavior = moveBehavior;
}
public String getWeaponType() {
return this.weaponBehavior.getWeaponType();
}
public abstract String getJobClass();
}
[Warrior.java] / Sub Class
public class Warrior extends Character {
String jobClass = "전사";
public Warrior(WeaponBehavior weapon) {
weaponBehavior = weapon;
moveBehavior = new WalkBehavior();
}
@Override
public String getJobClass() {
return jobClass;
}
}
[Client.java]
public class Client {
public static void main(String[] args) {
Character warrior = new Warrior(new Sword());
System.out.println("직업 : " +warrior.getJobClass());
System.out.println("무기 : " + warrior.getWeaponType());
warrior.performAttack();
warrior.performMove();
System.out.println();
warrior.setWeapon(new Axe());
warrior.setMoveBehavior(new RunBehavior());
System.out.println("직업 : " +warrior.getJobClass());
System.out.println("무기 : " + warrior.getWeaponType());
warrior.performAttack();
warrior.performMove();
}
}
장점
단점