Java Design Patterns Rookie series (13) State model modeling and implementation

Source: Internet
Author: User
Tags switch case

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

Related Article

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.