-
행위패턴 : State 패턴디자인패턴 2013. 3. 11. 09:00
분류 : 행위패턴(Behavioral Patterns)
정의 :
객체의 상태에 따라 동일 루틴에서 다른 행동을 하는 패턴
용도 :
소스
interface Statelike { /** * Writer method for the state name. * @param STATE_CONTEXT * @param NAME */ void writeName(final StateContext STATE_CONTEXT, final String NAME); } public class StateA implements Statelike { /** (non-Javadoc) * @see state.Statelike#writeName(state.StateContext, java.lang.String) */ @Override public void writeName(final StateContext STATE_CONTEXT, final String NAME) { System.out.println(NAME.toLowerCase()); STATE_CONTEXT.setState(new StateB()); } } public class StateB implements Statelike { /** State counter */ private int count = 0; /** (non-Javadoc) * @see state.Statelike#writeName(state.StateContext, java.lang.String) */ @Override public void writeName(final StateContext STATE_CONTEXT, final String NAME) { System.out.println(NAME.toUpperCase()); // Change state after StateB's writeName() gets invoked twice if(++count > 1) { STATE_CONTEXT.setState(new StateA()); } } } public class StateContext { private Statelike myState; /** * Standard constructor */ public StateContext() { setState(new StateA()); } /** * Setter method for the state. * Normally only called by classes implementing the State interface. * @param NEW_STATE */ public void setState(final Statelike NEW_STATE) { myState = NEW_STATE; } /** * Writer method * @param NAME */ public void writeName(final String NAME) { myState.writeName(this, NAME); } } public class TestClientState { public static void main(String[] args) { final StateContext SC = new StateContext(); SC.writeName("Monday"); SC.writeName("Tuesday"); SC.writeName("Wednesday"); SC.writeName("Thursday"); SC.writeName("Friday"); SC.writeName("Saturday"); SC.writeName("Sunday"); } }
참고자료
'디자인패턴' 카테고리의 다른 글
행위패턴 : Template Method 패턴 (0) 2013.03.25 행위패턴 : Strategy 패턴 (0) 2013.03.18 행위패턴 : Observer 패턴 (0) 2013.03.04 행위패턴 : Memento 패턴 (0) 2013.02.28 행위패턴 : Mediator 패턴 (0) 2013.02.28 댓글