전략 패턴(strategy pattern)

실행중에 알고리즘을 선택할 수 있게 하는 행위 소프트웨어 디자인 패턴

- 특정한 계열의 알고리즘을 정의

- 각 알고리즘을 캡슐화 하여 해당 계열 안에서 상호 교체가 가능하게 구현

전략 패턴을 구성하는 3가지 요소

1. 전략 메서드를 가진 전략 객체

2. 전략 객체를 사용하는 컨텍스트(전략 객체의 사용자/소비자)

3. 전략 객체를 생성해 컨텍스트에 주입하는 클라이언트(제 3자, 전략 객체의 공급자)

장점 – 코드 중복방지 , 런타임시 타겟 메소드 변경 ,확장성 및 알고리즘 변경 용이

*주 사용처 예시 *

주기적으로 오류 수정 및 업데이트가 필요한 프로그램 (온라인 게임)

계속적으로 서비스가 진행되어야하고 상황에 따라서 최적의 알고리즘이 필요한 코드 추가 및 수정시 해당 클래스만 추가 및 수정이 필요한 서버프로그래밍

전략 패턴 클래스 다이어그램

3줄요약

프로젝트 전체에서 변경이 일어나지 않는 부분에서 변경이 일어나는 부분을 찾아서 따로 캡슐화 한다

알고리즘 군을 정의하고 각각을 캡슐화하여 교환해서 사용할 수 있도록 만든다.

알고리즘을 사용하는 클라이언트와 독립적으로 알고리즘 변경이 가능하다.

내가 직접 짜본 전략 패턴 (이클립스 툴사용)

공격과 수비를 인터페이스로 나누고

직업군을 추상클래스로 나눠서 구성해보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
public abstract class Character2 {
    Act act;
    Sub sub;
    Sub sub2;
 
    public void Character2() {
 
    }
 
    public void Act() {
        act.Action();
 
    }
 
    public void Sub() {
        sub.subAction();
    }
 
    public void Sub2() {
        sub2.subAction();
    }
 
    public abstract void display();
 
}
 
cs
1
2
3
4
5
6
7
8
package test;
 
public interface Act {
    
    void Action();
 
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package test;
 
public class Warrior extends Character2 {
 
    public Warrior() {
 
        act = new powerAttack();
 
        sub = new heal();
        sub2 = new move();
 
    }
 
    public void display() {
        System.out.println("전사를 선택했습니다.");
    }
 
}
 
cs

 

ㅇㄴㅁㅇㄴㅁㅇㄴㅁㄴㅁㅇ

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package test;
 
import java.util.Scanner;
 
public class Client {
 
    public static void main(String[] args) {
 
        Character2 character = null;
        Scanner sc = new Scanner(System.in);
 
        battle bat = new battle();
        int selectNum = 0;
 
        while (true) {
            System.out.println("Character Select plz");
            System.out.println("1.전사   2.마법사  3.도적");
            System.out.print("Select Num : ");
            selectNum = sc.nextInt();
            switch (selectNum) {
 
            case 1:
                character = new Warrior();
                bat.battleContext(character, 1);
                break;
            case 2:
                character = new Wizard();
                bat.battleContext(character, 2);
                break;
 
            case 3:
                character = new Thief();
                bat.battleContext(character, 3);
                break;
 
            default:
                System.out.println("없는직업");
            }
        }
    }
 
}
 
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package test;
 
public class battle {
    int at , mv , heal ;
    public void battleContext(Character2 character, int sel) {
 
        Character2 thief = new Thief();
        at = 1;
        mv =0;
        heal =0;
    
        System.out.println("전투 시작");
        character.display();
 
        System.out.println(sel);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        
            e.printStackTrace();
        }
        System.out.println();
        int num = (int) (Math.random() * 50+ 40;
 
        for (int i = 0; i < num; i++) {
            int num2 = (int) (Math.random() * num) + 1;
            if (at % 4 == 0) {
        
        
                try {
                    at++;
                    character.Act();
                    continue;
                } catch (NullPointerException e) {
                    at--;
                }
            }
            if (num2 % 3 == 0) {
            
                at++;
                new attack().Action();
                
                try {
                
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    
                }
                continue;
            } else if (num2 % 4 == 0) {
                //new move().subAction();
                
                try {
                    Thread.sleep(100);
                    mv++;
                    character.Sub2();
                
                } catch (InterruptedException | NullPointerException e) {
                    // TODO Auto-generated catch block
                
                    mv--;
                }
                continue;
            } else if (num2 % 2 == 0) {
                // new heal().subAction();
                
                subSkill(character);
 
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        System.out.println("\nAttack:" + (at - 1+ " Move:" + mv + " Heal:" + heal);
 
        System.out.println("\n\n");
        
        
    }
    
    
    
    public void subSkill(Character2 character) {
        try{
            heal++;
            character.Sub();
            }
 
        catch (NullPointerException e){
            heal--;
        }
 
}
}
 
cs

이클립스 클래스 다이어그램 생성 툴 주소 :https://niceman.tistory.com/134

+ Recent posts