The state pattern of the Java design pattern

Source: Internet
Author: User

I. Overview

State mode can be used when an object in the system has more than one state, which can be converted between states, and the object behaves differently in different states. State mode separates the state of an object from the object and encapsulates it into a specialized state class, allowing the object state to vary flexibly. State mode is an object behavior pattern.


Second, the application scenario

It is used to solve the multiple state transitions of complex objects in the system and the encapsulation of behaviors in different states. In short, it is to deal with the various states of objects and their mutual transformations.


Third, UML class diagram


Iv. participants

1>, Abstractstate (Abstract state Class):

The abstract state class defines the behavior abstract methods in different states, while the subclasses (different state subclasses) implement different behavior actions.

2>, Concretestate (state subclass that implements behavior in a specific state):

Subclasses of the abstract State class, each of which implements a state-related behavior with the Environment Class (context), each of which corresponds to a specific state of the environment, with different specific states whose behavior differs.

3>, context (Environment class with State objects):

Owning a state attribute, because of the diversity of the environment, it can have different states and behave differently in different states. Maintains an abstract state instance in the environment class that defines the state of the current environment (the SetState () method), and separates the specific state behavior from the different state subclasses.


V. Use case Learning

1. Abstract State class: State.java

/** * Java design mode state mode * Abstract Status class * @author  [email protected] * */public abstract class State {/** * Status behavior abstraction method, by the specific state subclass to achieve the different The behavioral logic of */public abstract void Behavior ();}
2, the specific status sub-class A:concretestatea.java

/** * Specific status subclass A * @author  [email protected] */public class Concretestatea extends state {@Overridepublic void Behavior ( ) {//Status a business behavior, and when in that state, what to do//such as: mobile phone in the non-payment downtime, can normally dial the phone System.out.println ("mobile phone in the non-payment downtime, can call the normal phone");}}
3, the specific status sub-class B:concretestateb.java

/** * Specific Status sub-class B * @author  [email protected] * */public class Concretestateb extends state {@Overridepublic void Behavio R () {//State B's business behavior, and when it is in that state, what to do//such as: mobile phone in the case of under-cost shutdown, can not call the phone System.out.println ("mobile phone in arrears under the State, can not call");}}
4. Environment class with state object: Context.java
/** * Environment/Context class <br/> * have state objects and can complete transitions between states [state change/switchover implemented in environment class] * @author  [email protected] * */public class Context {//Maintain a reference to an abstract state object the private state state;/* * Sim Phone's call properties <br/> * Environment status as follows: * 1>, when  Bill >= 0.00$: Status normal   can also call c3/>* 2>, when  Bill < 0.00$: Cell phone arrears   cannot call */private double bill;/** * Environment handler function, invoke state instance behavior to complete business logic <br/> * According to different The state instance reference  handles different behaviors in different states */public void Handle () {checkstate (); Behavior ();} /** * Check Environment Status: State Change/switchover implemented in environment class */private void CheckState () {if (Bill >= 0.00) {setState (New Concretestatea ());} else {sets Tate (New Concretestateb ());}} /** * Set the environment state <br/> * Private method, the purpose is to let the state of the environment by the system environment itself to control/switch, the external user does not need to care about the environment inside the state * @param states */private void SetState {this.state = state;} Public double Getbill () {return bill;} public void Setbill (double bill) {this.bill = Bill;}}
5. Test client call class: Client.java
public class Client {public static void main (string[] args) {Context context = new Context (); Context.setbill (5.50); System.out.println ("Current Credit balance:" + context.getbill () + "$"), context. Handle (); Context.setbill (-1.50); System.out.println ("Current Credit balance:" + context.getbill () + "$"), context. Handle (); Context.setbill (50.00); System.out.println ("Current Credit balance:" + context.getbill () + "$"), context. Handle ();}}
6. Program Operation Result:
Current balance: 5.5$ mobile phone in the non-payment of downtime, can normally dial the current credit balance: -1.5$ mobile phone in arrears under the State, can not dial the current balance of the phone call: 50.0$ mobile phone in the non-payment of downtime, can call the normal

Vi.. Expansion

There are two different implementations of state switching in state mode

Mode one: The change/switchover of the State is implemented in the Environment class. such as the CheckState () method in the context class of the use case code above.

/** * Check Environment Status: State Change/switchover implemented in environment class */private void CheckState () {if (Bill >= 0.00) {setState (New Concretestatea ());} else {sets Tate (New Concretestateb ());}}

Mode two: The change/switchover of the State is implemented in the specific State subclass.

The implementation steps are as follows:

1> Initializes a state instance object in the Environment class context class and passes the environment context object as a construction parameter of the subclass state to the specific state subclass instance.

As in the Context.java class:

Set initial state this.state = new Concretestatea (this);
2> in the specific subclass state class, according to the context object constructed, the business logic judgment is checked and switched by invoking the property value of the context object.

such as in the specific state subclass Concretestatea.java class:

/** * Specific status subclass A * @author  [email protected] */public class Concretestatea extends state {private Context ctx;    Public Concretestatea (Context context) {    CTX = context;    } @Overridepublic void Behavior () {///status A's business behavior, and when it is in that state, what to do//such as: phone in the case of unpaid downtime, can normally call the phone System.out.println ("mobile phone in an unpaid shutdown state, Can call "); CheckState ();} /** * Check whether the state needs to be transformed by state <br/> * The transition of the State is implemented by the specific state subclass */private void CheckState () {if (Ctx.getbill () < 0.00) {Ctx.setstate (New Concretestateb (CTX));}}





The state pattern of the Java design pattern

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.