Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39829859
State mode: allows an object to change its behavior when the internal state changes , and the object looks as if it has modified its class. State mode It's just a matter of having a different state, a different state, a different behavior, and it's actually an extension of a statement like switch case .
First, UML modeling:
Second, the Code implementation
/** * Example: state mode-a pair of states with different state, different states corresponding to different behaviors * * below arithmetic for example */interface, public double operate (double NUM1, double num2); }/** * Addition */class Addoperator implements state {@Overridepublic double operate (double NUM1, double num2) {return num1 + nu M2;}} /** * Subtraction */class Suboperator implements state {@Overridepublic double operate (double NUM1, double num2) {return num1-num 2;}} /** * Student */class Student {private state state;public Student (state state) {this.state = state;} /** * Set status */public void SetState (state) {this.state = states;} Public double operate (double NUM1, double num2) {return state.operate (NUM1, num2);}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {Student S1 = new Student (New Ad Doperator ()); System.out.println (S1.operate (12, 23));/** * Change the state, i.e. change the behavior--the addition operation becomes the subtraction operation */s1.setstate (New Suboperator ()); System.out.println (S1.operate (12, 23));}}
Iii. Summary
Encapsulates the behavior of the base class state and delegates the behavior to the current state.
Java Design Patterns Rookie series (13) State model modeling and implementation