一、狀態(tài)模式(State Pattern)
類型:行為型模式
功能:
對象的行為依賴于它的狀態(tài)(屬性),并且可以根據(jù)它的狀態(tài)改變而改變它的相關(guān)行為。
二、例子
1、菜鳥教程例子
1.1、定義狀態(tài)接口
public interface State {
public void doAction(Context context);
}
1.2、定義開始狀態(tài)實現(xiàn)類
public class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
1.3、定義停止狀態(tài)實現(xiàn)類
public class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
1.4、創(chuàng)建 Context 類
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
1.5、使用 Context 來查看當狀態(tài) State 改變時的行為變化。
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
2、spring-statemachine-core源碼
三、其他設(shè)計模式
創(chuàng)建型模式
結(jié)構(gòu)型模式文章來源:http://www.zghlxwxcb.cn/news/detail-739970.html
- 1、設(shè)計模式——裝飾器模式(Decorator Pattern)+ Spring相關(guān)源碼
行為型模式文章來源地址http://www.zghlxwxcb.cn/news/detail-739970.html
- 1、設(shè)計模式——訪問者模式(Visitor Pattern)+ Spring相關(guān)源碼
- 2、設(shè)計模式——中介者模式(Mediator Pattern)+ JDK相關(guān)源碼
- 3、設(shè)計模式——策略模式(Strategy Pattern)+ Spring相關(guān)源碼
- 4、設(shè)計模式——狀態(tài)模式(State Pattern)
- 5、設(shè)計模式——觀察者模式(Observer Pattern)+ Spring相關(guān)源碼
到了這里,關(guān)于設(shè)計模式——狀態(tài)模式(State Pattern)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!