Java Design Pattern cainiao series (13) state pattern modeling and implementation

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.