introduce
The behavior of a state pattern is parallel and irreplaceable. Policy pattern behaviors are independent and replaceable. State pattern is intended to change the behavior of an object when its internal state changes.
UML
Example
Press the program button to select the selection mode when the power is turned on. Press the water volume button to select the water volume, etc. When the power is off, the click of program button and water button has no effect.
A simple Java example is roughly as follows:
- Define an interface to provide two methods for button execution:
public interface IKeyBoardOp {
/**
* Choice mode
*/
void chooseModel();
/**
* Selective water volume
*/
void chooseWaterNum();
}
- Define implementation classes and provide different implementations for different business States
/**
* Key implementation class in case of power off
*/
public class PowerOFFImpl implements IKeyBoardOp {
@Override
public void chooseModel() {
System.out.println("Power off, no operation");
}
@Override
public void chooseWaterNum() {
System.out.println("Power off, no operation");
}
}
/**
* Key implementation class with power on
*/
public class PowerOnImpl implements IKeyBoardOp {
/**
* Pattern
*/
private int model = 1;
/**
* Water quantity
*/
private int waterNum = 1;
@Override
public void chooseModel() {
System.out.println("Pattern" + model++ + "");
}
@Override
public void chooseWaterNum() {
System.out.println("Water quantity" + waterNum++ + "");
}
}
- The protagonist, the functional business class, holds the status class and calls the state control related business implementation in the corresponding business.
/**
* State mode context class
*/
public class KeyBoardModel {
/**
* Hold the function control interface to reflect the state
*/
private IKeyBoardOp iKeyBoardOp;
public KeyBoardModel(IKeyBoardOp iKeyBoardOp) {
this.iKeyBoardOp = iKeyBoardOp;
}
/**
* Update state
*
* @param iKeyBoardOp New state
*/
public void setiKeyBoardOp(IKeyBoardOp iKeyBoardOp) {
this.iKeyBoardOp = iKeyBoardOp;
}
/**
* Choice mode
*/
public void chooseModel() {
iKeyBoardOp.chooseModel();
}
/**
* Selective water volume
*/
public void chooseWaterNum() {
iKeyBoardOp.chooseWaterNum();
}
}
In this way, a simple state mode is implemented. Is it very simple? Is it similar to the strategy mode. In fact, from another perspective, the implementation of the business function can also be seen as a strategy mode, different strategies, and finally different businesses. Wifi control in Android uses state mode.
Summary: the state mode and the policy mode are mainly from different perspectives. Of course, the state mode is broader and more global. For the whole object, it is more suitable for some situations with enabling switches.