1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public class VendingMachine { private enum State { Selling { @Override public void sendMessage() { System.out.println( "Selling" ); } }, SoldOut { @Override public void sendMessage() { System.out.println( "Sold out" ); } }; public abstract void sendMessage(); } private State state; public VendingMachine() { setState(State.Selling); } public void pullLever() { if (state == State.SoldOut) { System.out.println( "Already sold out" ); } else if ( new Random().nextBoolean()) { setState(State.SoldOut); } else { state.sendMessage(); } } private void setState(State state) { this .state = state; state.sendMessage(); } public static void main(String[] args) { VendingMachine machine = new VendingMachine(); for ( int i = 0 ; i < 10 ; i++) { System.out.print( "Pull the lever: " ); machine.pullLever(); } } } |
'Archive' 카테고리의 다른 글
Chain Constructors (연쇄 생성자) (0) | 2012.01.24 |
---|---|
Dependency Injection (의존성 주입) (0) | 2012.01.24 |
Anonymous class를 사용한 Command 패턴들의 Singleton (0) | 2012.01.24 |
한글 띄워쓰기 쉽게 교정하는 방법 (1) | 2012.01.17 |
Eclipse에서 Shift + Enter 기능 (0) | 2012.01.15 |