1.Strategy Design Pattern

1. 학습목표

  • Interface
  • Delegate
  • Strategy Pattern

1.1. Interface

키보드나 디스플레이 따위 처럼 사람과 컴퓨터를 연결하는 장치

  • 기능에 대한 선언과 구현을 분리
  • 기능을 사용 통로

기능을 기능의 선언과 기능의 구현을 분리할 수 있는 기능을 제공한다.

1.2. Delegate

특정 객체의 기능을 사용하기 위하여 다른객체의 기능을 호출하는것.

1.3. Strategy Pattern

여러 알고리즘을 하나의 추상적인 접근점을 만들어서 접근점에서 서로 교환이 가능하도록 하도록 하는 패턴

Strategy Pattern

2. Code

아래의 코드는 Strategy 디자인 패턴을 알아보기위하여 게임에서 캐릭터가 스킬 사용에 있어서 Strategy 디자인을 적용하였습니다. 하나의 캐릭터가 스킬을 사용한다고 가정하는 예제입니다.

즉, Weapon이라고하는 접근점에서 Delegate하여 공격에 대한 기능을 호출하는 방식입니다.

main class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package StrategyPattern;
import StrategyPattern.Delegate.AObj;
import StrategyPattern.Interface.AInterface;
import StrategyPattern.Interface.AInterfaceImpl;

public class Main {
public static void main(String[] args) {
GameCharacter character = new GameCharacter();
character.attack();

character.setWeapon(new Knife());
character.attack();

character.setWeapon(new Sword());
character.attack();

character.setWeapon(new Ax());
character.attack();

}
}

weapon Interface

1
2
3
4
5
6
package StrategyPattern;

public interface Weapon {
public void attack();
}

Character class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package StrategyPattern;
public class GameCharacter {
// 접근
private Weapon weapon;

// 교환점
public void setWeapon(Weapon weapon){
this.weapon = weapon;
}

public void attack(){
if(weapon == null){
System.out.println("Hand Attack!");
}else {
weapon.attack();
}
}
}

Ax class

1
2
3
4
5
6
7
8
package StrategyPattern;

public class Ax implements Weapon{
@Override
public void attack() {
System.out.println("Ax Attack!");
}
}

Knife class

1
2
3
4
5
6
7
8
9
10
package StrategyPattern;

import StrategyPattern.Weapon;

public class Knife implements Weapon {
@Override
public void attack() {
System.out.println("Knife Attack!");
}
}

Sword class

1
2
3
4
5
6
7
package StrategyPattern;
public class Sword implements Weapon {
@Override
public void attack() {
System.out.println("Sword Attack!");
}
}