写在前头:希望你了解到的不仅是模式,而学会用OOP的眼光分析问题,解决问题
关键字:封装变化
描述:避免if与switch语句。分离抽象出状态,再通过组合建立联系
原则:往往需要修改的,就是需要封装的,需要明确职责的;就需要考虑单一职责和开放封闭原则。
示例:pull & push改变把手行为颜色
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| public interface State { public void pull(PaintBoard paintBoard); public void push(PaintBoard paintBoard); public String name(); }
public class RedState implements State {
@Override public void pull(PaintBoard paintBoard) { paintBoard.setState(new YellowState()); } @Override public void push(PaintBoard paintBoard) { paintBoard.setState(new GreenState()); } @Override public String name() { return "RED"; }
}
public class GreenState implements State {
@Override public void pull(PaintBoard paintBoard) { paintBoard.setState(new RedState()); }
@Override public void push(PaintBoard paintBoard) { paintBoard.setState(new YellowState()); }
@Override public String name() { return "Green"; }
}
public class YellowState implements State {
@Override public void pull(PaintBoard paintBoard) { paintBoard.setState(new GreenState()); }
@Override public void push(PaintBoard paintBoard) { paintBoard.setState(new RedState()); }
@Override public String name() { return "Yellow"; }
}
public class PaintBoard { private State state; public PaintBoard() { this.state=new RedState(); } public PaintBoard(State state) { this.state=state; } public void push() { state.push(this); } public void pull() { state.pull(this); } public void setState(State state) { this.state=state; } public String getCurrentClolor() { return state.name(); } public static void main(String[] args) { PaintBoard paintBoard= new PaintBoard(); System.out.println("Origin Color:"+paintBoard.getCurrentClolor()); for(int i=0; i<3; i++) { System.out.print(paintBoard.getCurrentClolor()); paintBoard.pull(); System.out.println("->pull->"+paintBoard.getCurrentClolor()); } System.out.println(); for(int i=0; i<3; i++) { System.out.print(paintBoard.getCurrentClolor()); paintBoard.push(); System.out.println("->pull->"+paintBoard.getCurrentClolor()); } } }
|