設計模式——20狀態模式(State)

inzaghi1984發表於2017-12-11

20、狀態模式(State)
核心思想就是:當物件的狀態改變時,同時改變其行為,很好理解!就拿QQ來說,有幾種狀態,線上、隱身、忙碌等,每個狀態對應不同的操作,而且你的好友也能看到你的狀態,所以,狀態模式就兩點:1、可以通過改變狀態來獲得不同的行為。2、你的好友能同時看到你的變化。

State類是個狀態類,Context類可以實現切換,我們來看看程式碼:

[java] view plaincopy

  1. package com.xtfggef.dp.state;
  2. /**
    • 狀態類的核心類
    • 2012-12-1
    • @author erqing
  3. */
  4. public class State {
  5. private String value;
  6. public String getValue() {
  7. return value;
  8. }
  9. public void setValue(String value) {
  10. this.value = value;
  11. }
  12. public void method1(){
  13. System.out.println(“execute the first opt!”);
  14. }
  15. public void method2(){
  16. System.out.println(“execute the second opt!”);
  17. }
  18. }
    [java] view plaincopy
  19. package com.xtfggef.dp.state;
  20. /**
    • 狀態模式的切換類 2012-12-1
    • @author erqing
  21. */
  22. public class Context {
  23. private State state;
  24. public Context(State state) {
  25. this.state = state;
  26. }
  27. public State getState() {
  28. return state;
  29. }
  30. public void setState(State state) {
  31. this.state = state;
  32. }
  33. public void method() {
  34. if (state.getValue().equals(“state1”)) {
  35. state.method1();
  36. } else if (state.getValue().equals(“state2”)) {
  37. state.method2();
  38. }
  39. }
  40. }
    測試類:

[java] view plaincopy

  1. public class Test {
  2. public static void main(String[] args) {
  3. State state = new State();
  4. Context context = new Context(state);
  5. //設定第一種狀態
  6. state.setValue(“state1”);
  7. context.method();
  8. //設定第二種狀態
  9. state.setValue(“state2”);
  10. context.method();
  11. }
  12. }
    輸出:

execute the first opt!
execute the second opt!
根據這個特性,狀態模式在日常開發中用的挺多的,尤其是做網站的時候,我們有時希望根據物件的某一屬性,區別開他們的一些功能,比如說簡單的許可權控制等。


相關文章