Java 객체지향 디자인 패턴 5장 스트래티지

필자의 해석이 포함되어 있습니다!
실제로 책에서 의도한 의미와는 다를 수 가 있습니다
주의 부탁드립니다 !!

5장 : Strategy. 전략


  • 이 전략을 만족시켜야
  • OCP 를 만족하는 설계가 된다
  • 아래는 주 구현 코드이다
public class StrategyMain {

	abstract static class Robot {

		private String name;
		private AttackStrategy attackStrategy;
		private MovingStrategy movingStrategy;

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

		public void attack() {
			String message = attackStrategy.attack();
			System.out.println(name + " " + message);
		}

		public void move() {
			String message = movingStrategy.move();
			System.out.println(name + " " + message);
		}

		public abstract void setAttackStrategy(AttackStrategy attackStrategy);

		public abstract void setMovingStrategy(MovingStrategy movingStrategy);
	}

	interface MovingStrategy {
		String move();
	}

	interface AttackStrategy {
		String attack();
	}

	static class PunchAttackStrategy implements AttackStrategy {

		@Override
		public String attack() {
			return "주먹으로 공격합니다";
		}
	}

	private static class KickAttackStrategy implements AttackStrategy {

		@Override
		public String attack() {
			return "발차기로 공격합니다";
		}
	}

	private static class RunningMovingStrategy implements MovingStrategy {

		@Override
		public String move() {
			return "달려 갑니다";
		}
	}

	private static class FlyingMovingStrategy implements MovingStrategy {

		@Override
		public String move() {
			return "날아 갑니다";
		}
	}

	static class TaekwonV extends Robot {

		public TaekwonV(String name) {
			super(name);
		}

		@Override
		public void setAttackStrategy(AttackStrategy attackStrategy) {
			super.attackStrategy = attackStrategy;
		}

		@Override
		public void setMovingStrategy(MovingStrategy movingStrategy) {
			super.movingStrategy = movingStrategy;
		}
	}

	static class Atom extends Robot {

		public Atom(String name) {
			super(name);
		}

		@Override
		public void setAttackStrategy(AttackStrategy attackStrategy) {
			super.attackStrategy = attackStrategy;
		}

		@Override
		public void setMovingStrategy(MovingStrategy movingStrategy) {
			super.movingStrategy = movingStrategy;
		}
	}

	static class Client {

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

			taekwonV.setAttackStrategy(new PunchAttackStrategy());
			atom.setAttackStrategy(new KickAttackStrategy());

			taekwonV.setMovingStrategy(new RunningMovingStrategy());
			atom.setMovingStrategy(new FlyingMovingStrategy());

			taekwonV.attack();
			taekwonV.move();

			atom.attack();
			atom.move();
		}

	}
}




© 2020.12. by 따라쟁이

Powered by philz