
전략 인터페이스
public interface IBehaviorStrategy {
public void behave(String context);
}
전략 클래스
public class DanceStrategy implements IBehaviorStrategy{
@Override
public void behave(String context) {
// TODO Auto-generated method stub
System.out.println(context + " 상황~ 개구쟁이 모드");
System.out.println("엉덩이 춤을 추자");
}
}
public class HeroStrategy implements IBehaviorStrategy{
@Override
public void behave(String context) {
// TODO Auto-generated method stub
System.out.println(context + " 상황! 액션가면 출동");
System.out.println("정의의 이름으로 악당을 물리친다");
}
}
public class SleepStrategy implements IBehaviorStrategy{
@Override
public void behave(String context) {
// TODO Auto-generated method stub
System.out.println(context + " 상황......갑자기 졸리다 zzzzz");
System.out.println("눈을 감고 상황을 회피하자");
}
}
Context 클래스
public class 짱구 {
private IBehaviorStrategy strategy = null;
public void setStrategy(IBehaviorStrategy strategy){ //외부에서 주입 받음
this.strategy = strategy;
System.out.println("현재 짱구의 매너전략: "+this.strategy.getClass().getSimpleName());
}
//필수적이지 않지만
public void encountSituation(String situation) {
System.out.println("[상황 발생]"+ situation);
if (this.strategy == null) {
System.out.println("현재 전략 없음....무념무상...멍......");
return;
}
this.strategy.behave(situation);
}
}
'JAVA' 카테고리의 다른 글
| [JAVA] 중간고사 대비 (0) | 2025.10.19 |
|---|---|
| [JAVA] 디자인 패턴 - 템플릿 메소드 (0) | 2025.10.17 |
| [JAVA] 커피메이커 Ver.1 (3) | 2025.10.01 |
| [JAVA] Thread (0) | 2025.09.24 |
| [JAVA] Generic & Collection (0) | 2025.09.19 |