Posted:      Updated:

자바 디자인 패턴 스터디를 하며 ‘Java 객체 지향 디자인 패턴’ 교재를 정리한 글입니다.

스트래티지 패턴(Strategy Pattern)

  • 전략을 쉽게 바꿀 수 있도록 해주는 디자인 패턴
  • 전략: 어떤 목적을 달성하기 위해 일을 수행하는 방식, 비즈니스 규칙, 문제를 해결하는 알고리즘 등
  • 같은 문제를 해결하는 여러 알고리즘이 클래스별로 캡슐화되어 있음
  • 필요할 때 교체할 수 있도록 함
  • 동일한 문제를 다른 알고리즘으로 해결
  • 기존의 구조를 변경시키지 않고 새로운 전략 추가, 변경 가능

스트래티지 패턴 컬레보레이션

  • Strategy
    • 인터페이스나 추상 클래스
    • 외부에서 동일한 방식으로 알고리즘 호출하는 방법 명시
  • ConcreteStrategy1, 2, 3
    • 알고리즘 실제 구현 클래스
  • Context
    • 스트래티지 패턴을 이용하는 클래스
    • 여러 전략을 사용
    • 필요에 따라 동적으로 구체적인 전략 변경

예시: 로봇 만들기

  • 아톰, 태권V 두 가지의 로봇이 있음
  • 기존 로봇 공격, 이동 방법을 편리하게 수정, 추가
  • 새로운 로봇을 편리하게 추가 가능

구현 방법

  • 변화되는 요인인 이동 방식과 공격 방식을 클래스로 캡슐화
  • 외부에서 구체적인 이동 방식, 공격 방식을 담은 클래스 은닉
  • 공격, 이동을 위한 인터페이스 만들기

전체 코드

public abstract class Robot {
    private String name;
    private MovingStrategy movingStrategy;
    private AttackStrategy attackStrategy;

    public Robot(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void move() {
        movingStrategy.move();
    }

    public void attack() {
        attackStrategy.attack();
    }

    public void setMovingStrategy(MovingStrategy movingStrategy) {
        this.movingStrategy = movingStrategy;
    }

    public void setAttackStrategy(AttackStrategy attackStrategy) {
        this.attackStrategy = attackStrategy;
    }
}

public class TaekwonV extends Robot{
    public TaekwonV(String name) {
        super(name);
    }
}

public class Atom extends Robot {
    public Atom(String name) {
        super(name);
    }
}

public interface MovingStrategy {
    public void move();
}

public class FlyingStrategy implements MovingStrategy {
    public void move() {
        System.out.println("I can fly.");
    }
}

public class WalkStrategy implements MovingStrategy {
    @Override
    public void move() {
        System.out.println("I can only walk.");
    }
}

public interface AttackStrategy {
    public void attack();
}

public class MissileStrategy implements AttackStrategy {
    @Override
    public void attack() {
        System.out.println("I have Missile and can attack with it.");
    }
}

public class PunchStrategy implements AttackStrategy {
    @Override
    public void attack() {
        System.out.println("I have strong punch and can attack with it.");
    }
}

public class Main {
    public static void main(String[] args) {
        Robot taekwonV = new TaekwonV("Taekwonv");
        Robot atom = new Atom("Atom");

        taekwonV.setMovingStrategy(new WalkStrategy());
        taekwonV.setAttackStrategy(new MissileStrategy());

        atom.setMovingStrategy(new FlyingStrategy());
        atom.setAttackStrategy(new PunchStrategy());

        System.out.println("My name is "+ taekwonV.getName());
        taekwonV.move();
        taekwonV.attack();
        System.out.println();
        System.out.println("My name is "+ atom.getName());
        atom.move();
        atom.attack();
    }
}

출력

My name is Taekwonv
I can only walk.
I have Missile and can attack with it.

My name is Atom
I can fly.
I have strong punch and can attack with it.

댓글남기기