設計模式(行爲型模式)——狀態模式(State)

核心思想就是:當對象的狀態改變時,同時改變其行爲,很好理解!就拿QQ來講,有幾種狀態,在線、隱身、忙碌等,每一個狀態對應不一樣的操做,並且你的好友也能看到你的狀態,因此,狀態模式就兩點:一、能夠經過改變狀態來得到不一樣的行爲。二、你的好友能同時看到你的變化。看圖:java

State類是個狀態類,Context類能夠實現切換,咱們來看看代碼:測試

package com.xtfggef.dp.state;  
  
/** 
 * 狀態類的核心類 
 * 2012-12-1 
 * @author erqing 
 * 
 */  
public class State {  
      
    private String value;  
      
    public String getValue() {  
        return value;  
    }  
  
    public void setValue(String value) {  
        this.value = value;  
    }  
  
    public void method1(){  
        System.out.println("execute the first opt!");  
    }  
      
    public void method2(){  
        System.out.println("execute the second opt!");  
    }  
}
package com.xtfggef.dp.state;  
  
/** 
 * 狀態模式的切換類   2012-12-1 
 * @author erqing 
 *  
 */  
public class Context {  
  
    private State state;  
  
    public Context(State state) {  
        this.state = state;  
    }  
  
    public State getState() {  
        return state;  
    }  
  
    public void setState(State state) {  
        this.state = state;  
    }  
  
    public void method() {  
        if (state.getValue().equals("state1")) {  
            state.method1();  
        } else if (state.getValue().equals("state2")) {  
            state.method2();  
        }  
    }  
}

測試類:網站

public class Test {  
  
    public static void main(String[] args) {  
          
        State state = new State();  
        Context context = new Context(state);  
          
        //設置第一種狀態  
        state.setValue("state1");  
        context.method();  
          
        //設置第二種狀態  
        state.setValue("state2");  
        context.method();  
    }  
}

輸出:this

 

execute the first opt!
execute the second opt!code

根據這個特性,狀態模式在平常開發中用的挺多的,尤爲是作網站的時候,咱們有時但願根據對象的某一屬性,區別開他們的一些功能,好比說簡單的權限控制等。對象

相關文章
相關標籤/搜索