Share a big man’s artificial intelligence tutorial. Zero foundation! Easy to understand! Funny and humorous! I hope you will join the team of artificial intelligence too! Please clickArtificial Intelligence Tutorial
Let's talk about a simple example. The most basic requirement for commodity inventory centers is to reduce inventory and replenish inventory. Let’s see how to write it using the status model.
The core is that our focus is no longer on which operation Context should be performed, but on what operations this Context will have.
Define the status interface:
public interface State {
public void doAction(Context context);
}
Define the status of inventory reduction:
public class DeductState implements State {
public void doAction(Context context) {
("Sell goods, prepare to reduce inventory");
(this);
// Perform the specific operation of reducing inventory...
}
public String toString() {
return "Deduct State";
}
}
Define the state of replenishment:
public class RevertState implements State {
public void doAction(Context context) {
("Replenish inventory of this product");
(this);
// Perform the specific operation of replenishing inventory...
}
public String toString() {
return "Revert State";
}
}
I used (this) before, let’s see how to define the Context class:
public class Context {
private State state;
private String name;
public Context(String name) {
= name;
}
public void setState(State state) {
= state;
}
public void getState() {
return ;
}
}
Let’s take a look at the client calls and you will know clearly:
public static void main(String[] args) {
// What we need to operate is iPhone X
Context context = new Context("iPhone X");
// See how to replenish inventory
State revertState = new RevertState();
(context);
// Similarly, the operation of reducing inventory is very simple
State deductState = new DeductState();
(context);
// If necessary, we can get the current state
().toString();
}
Readers may find that in the above example, if we do not care about what state the current context is in, then the Context will no longer need to maintain the state attribute, and the code will be much simpler.
However, the example of commodity inventory is just an isolated case after all, and we still have many instances that need to know what state the current context is in.