[JAVA 디자인패턴] Strategy패턴
- JAVA/디자인패턴
- 2018. 5. 1. 15:20
Strategy패턴이란
Strategy패턴이란 직역하면 전략패턴의 의미로 여러 알고리즘을 하나의 추상적인 접근점(=인터페이스)을 만들어 서로 교체가능(setMethod) 하도록 구현하는 패턴이다. 말로만 설명하면 굉장히 복잡하게 느껴지지만, MVC 패턴의 DAO를 인터페이스로 선언하고 구현하거나, Spring DI를 적용하때 인터페이스를 구현하는 것 역시 모두 Strategy패턴에 속한다.
Strategy패턴 UML
- Client : Strategy Interface를 has a 관계로 소유하고 있는 클래스이다.
- Strategy Interface : Client클래스와 Strategy Implements 클래스들의 연결점이 되는 추상적인 접근점.
- Strategy Implements : 실제로 수행될 다양한 Strategy(알고리즘/기능)의 구현체로 Client에게 사용되어진다.
Strategy패턴 예시
GameUser Class
- Weapon weapon을 has 하고 있는 관계
- User가 attack() 수행시 weapon 인터페이스를 조작
- weapon Object는 Interface로 선언되어 setWeapon을 통해 다른 무기로 변경가능
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class GameUser { // 추상적인 접근점 private IWeapon weapon; // 교환가능 public void setWeapon(IWeapon weapon) { this.weapon = weapon; } public void attack() { if(weapon == null) { System.out.println("멘손 공격"); } else { weapon.attack(); } } } | cs |
IWeapon Interface
- Strategy패턴의 핵심 인터페이스
1 2 3 4 5 | public interface IWeapon { public void attack(); } | cs |
IWeapon의 구현체 클래스들
1 2 3 4 5 6 | public class Sword implements IWeapon { @Override public void attack() { System.out.println("검 공격"); } } | cs |
1 2 3 4 5 6 | public class Knife implements IWeapon { @Override public void attack() { System.out.println("칼 공격"); } } | cs |
1 2 3 4 5 6 | public class Gun implements IWeapon { @Override public void attack() { System.out.println("총 공격"); } } | cs |
Main Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Main { public static void main(String[] args) { GameUser user = new GameUser(); user.attack(); user.setWeapon(new Knife()); user.attack(); user.setWeapon(new Sword()); user.attack(); user.setWeapon(new Gun()); user.attack(); } } | cs |
수행결과
멘손 공격
칼 공격
검 공격
총 공격
참고 :
'JAVA > 디자인패턴' 카테고리의 다른 글
[JAVA 디자인패턴] Builder 패턴 정리 (0) | 2018.05.02 |
---|---|
[JAVA 디자인패턴] Singleton 패턴의 모든 것 (멀티스레드 고려) (1) | 2018.05.02 |
이 글을 공유하기