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

 

 

 

 

ex> 요구사항

- 신작 게임에서 캐리거와 무기를 구현해보세요.
- 무기는 두가지 종류가 있습니다.

 

=> 무기들을 접근점으로 만들어준다.

-------------------------------------

1
2
3
public interface Weapon {
 public void attack();
}
cs

 

1
2
3
4
5
6
7
public class knife implements Weapon{
 
 @Override
 public void attack() {
  System.out.println("칼 공격");
 {
}
cs

 

1
2
3
4
5
6
7
public class Sword implements Weapon{
 
 @Override
 public void attack() {
  System.out.println("검 공격");
 {
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 //접근점
 private Weapon weapon;
 
 // 교환 가능
 public void setWeapon(Weapon weapon) {
  this.weapon = weapon;
 }
 
 public void attack() {
 
  if(weapon == null) {
   System.out.println("맨손 공격");
  } else {
 
   //델리 게이트 => 칼일지 검일지 나는 모른다.weapon이 알아서 할거다.
   weapon.attack();
  }
 } 
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
public class Main {
 public static void main(String[] args) {
  GameCharacter gc = new GameCharacter();
  gc.attack();   // 맨손 공격
 
  gc.setWeapon(new Knife());
  gc.attack();   // 칼 공격
  gc.setWeapon(new Sword()); 
  gc.attack();   // 검 공격
 }
}
cs

 

 

 


 

 

+ Recent posts