// State Pattern
// 객체의 상태가 바뀔때마다 행위가 바뀌게 되는 객체들을 '조직화' 하는 디자인 기법
- // Item의 상태에 따라 캐릭터의 동작을 변경
- // 캐릭터의 동작을 정의한 인터페이스 생성
- interface IState {
- public void run();
- public void attack();
- }
- class NormalState implements IState {
- @Override
- public void run() {
- System.out.println("run");
- }
- @Override
- public void attack() {
- System.out.println("attack");
- }
- }
- class FastState implements IState {
- @Override
- public void run() {
- System.out.println("fast run");
- }
- @Override
- public void attack() {
- System.out.println("fast attack");
- }
- }
- class SlowState implements IState {
- @Override
- public void run() {
- System.out.println("slow run");
- }
- @Override
- public void attack() {
- System.out.println("slow attack");
- }
- }
- class Character {
- private int gold;
- private IState state;
- public Character(NormalState normalState) {
- state = normalState;
- }
- public void setState(IState state) {
- this.state = state;
- }
- // Replace type code with Polymorphism
- // 상속을 통한 오버라이딩
- public void run() {
- state.run();
- }
- public void attack() {
- state.attack();
- }
- public void useGold(int i) {
- gold -= i;
- System.out.println("put " + i + " / " + gold);
- }
- public void addGold(int i) {
- gold += i;
- System.out.println("get " + i + " / " + gold);
- }
- }
- public class Ex3 {
- public static void main(String...args) {
- Character c = new Character(new NormalState());
- IState f = new FastState();
- IState s = new SlowState();
- c.run();
- // item
- c.setState(f);
- c.run();
- c.addGold(100);
- c.setState(s);
- c.run();
- }
- }
'java > design_pattern' 카테고리의 다른 글
Flyweight Pattern (0) | 2014.06.27 |
---|---|
Prototype Pattern (0) | 2014.06.27 |
Decorator Pattern (0) | 2014.06.27 |
Composite Pattern (0) | 2014.06.27 |
Strategy Pattern (0) | 2014.06.27 |