Java Design Pattern cainiao series (13) state pattern modeling and implementation
State: allows an object to change its behavior when its internal State changes. The object seems to have modified its class. To put it bluntly, the state mode refers to the expansion of statements such as switch case, which have different States and different States correspond to different behaviors.
I. uml modeling:
Ii. Code Implementation
/*** Example: State mode-A object has a different state, different States correspond to different behaviors ** the following four operations are taken as an example */interface State {public double operate (double num1, double num2 );} /*** addition */class AddOperator implements State {@ Overridepublic double operate (double num1, double num2) {return num1 + num2 ;}} /*** subtraction */class SubOperator implements State {@ Overridepublic double operate (double num1, double num2) {return num1-num2 ;}} /*** Student */class Student {private State state State; public Student (state State state) {this. state = state;}/*** set State */public void setState (state) {this. state = state;} 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 AddOperator (); System. out. println (s1.operate (12, 23);/*** changes the status, that is, changes the behavior --> the addition operation changes to the subtraction operation */s1.setState (new SubOperator ()); system. out. println (s1.operate (12, 23 ));}}
Iii. Summary
Encapsulate the behavior of the base class status and delegate the behavior to the current status.