[Design pattern] Strategy Pattern πŸ”, (Behavioral patterns)

홍정완·2021λ…„ 8μ›” 10일
0

Design pattern

λͺ©λ‘ 보기
6/7
post-thumbnail

Strategy Pattern πŸ”

같은 κΈ°λŠ₯μ΄μ§€λ§Œ μ„œλ‘œ λ‹€λ₯Έ μ „λž΅μ„ 가진 class듀을 각각 μΊ‘μŠν™”ν•˜μ—¬ μƒν˜Έκ΅ν™˜ν•  수 μžˆλ„λ‘ ν•˜λŠ” νŒ¨ν„΄



ꡬ쑰


  • Context

    • Strategy μΈν„°νŽ˜μ΄μŠ€λ₯Ό μœ„μž„
    • ν΄λΌμ΄μ–ΈνŠΈκ°€ 직접 μ‚¬μš©ν•˜λŠ” class
  • Strategy

    • ꡬ체적인 μ•Œκ³ λ¦¬μ¦˜μ˜ 곡동 μŠ€νŽ™μ„ μ •μ˜ν•˜λŠ” class
  • ConcreteStrategy

    • ꡬ체적인 μ•Œκ³ λ¦¬μ¦˜μ„ κ΅¬ν˜„ν•˜λŠ” class


μž₯점

  • 상황에 따라 μœ μ§€ 보수 용이

  • μ•Œκ³ λ¦¬μ¦˜ κ΅¬ν˜„λΆ€μ™€ μ‚¬μš©λΆ€κ°€ 뢄리

    • μ‚¬μš©μžκ°€ μ•Œκ³ λ¦¬μ¦˜μ„ 일관성 있게 μ‚¬μš© κ°€λŠ₯

    • 각 μ•Œκ³ λ¦¬μ¦˜λ“€μ€ λ™μΌν•œ μΈν„°νŽ˜μ΄μŠ€λ₯Ό 가진닀.

    • λͺ©μ μ— 따라 λ‹€λ₯΄κ²Œ κ΅¬ν˜„ κ°€λŠ₯


단점

  • μ•Œκ³ λ¦¬μ¦˜ μˆ˜κ°€ μ¦κ°€ν• μˆ˜λ‘ 객체 수 증가


  • μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” 정보듀도 μ•Œκ³ λ¦¬μ¦˜μ— 포함

    • [μ˜ˆμ™Έ 1] ꡬ체적인 μ•Œκ³ λ¦¬μ¦˜λ“€λ§ˆλ‹€ ν•„μš”ν•œ μž…λ ₯ νŒŒλΌλ―Έν„°κ°€ λ‹€λ₯Ό 수 μžˆλ‹€.

    • [μ˜ˆμ™Έ 2] μΈν„°νŽ˜μ΄μŠ€λ‘œ νŒŒλΌλ―Έν„°κ°€ κ³ μ •,
      κ·Έλ ‡κΈ° λ•Œλ¬Έμ— μ•Œκ³ λ¦¬μ¦˜μ— ν•„μš” μ—†λŠ” νŒŒλΌλ―Έν„°λ„ λ‹€ λ°›κ²Œ λœλ‹€.


ν™œμš© 상황

  • μ•Œκ³ λ¦¬μ¦˜(μ „λž΅)을 ν΄λΌμ΄μ–ΈνŠΈκ°€ μ •ν•΄μ•Ό ν•  λ•Œ

  • 동일 κ³„μ—΄μ˜ μ•Œκ³ λ¦¬μ¦˜λ“€μ„ μΈν„°νŽ˜μ΄μŠ€λ‘œ ν†΅μΌν•˜μ—¬ μ œκ³΅ν•  λ•Œ



κ΅¬ν˜„


interface CoffeeStrategy {
	
	public abstract String brew();
}

public class AmericanoStrategy implements CoffeeStrategy {

	private static final String AMERICANO = "아메리카노";

	@Override
	public String brew() {
		return AMERICANO;
	}
}

public class CafeLatteStrategy implements CoffeeStrategy {

	private static final String CAFE_LATTE = "μΉ΄νŽ˜λΌλ–Ό";

	@Override
	public String brew() {
		return CAFE_LATTE;
	}
}

public class CoffeeMachine {

	public String brew(CoffeeStrategy coffeestrategy) {
		return coffeestrategy.brew();
	}
}

public class Main {

	public static void main(String[] args) {

		CoffeeMachine coffeeMachine = new CoffeeMachine();

		String americano = coffeeMachine.brew(americanoButton());
		System.out.println(americano);

		String cafelatte = coffeeMachine.brew(cafeLatteButton());
		System.out.println(cafelatte);

	}

	public static CoffeeStrategy americanoButton() {
		return new AmericanoStrategy();
	}

	public static CoffeeStrategy cafeLatteButton() {
		return new CafeLatteStrategy();
	}
}

profile
μŠ΅κ΄€μ΄ μ „λΆ€λ‹€.

0개의 λŒ“κΈ€