23 design patterns (22) java state patterns, 23 Design Patterns

Source: Internet
Author: User

23 design patterns (22) java state patterns, 23 Design Patterns

I. Overview

When an object in the system has multiple states, these States can be converted, and the state mode can be used for different states of the object. The State mode separates the state of an object from the object and encapsulates it into a special State class, so that the state of the object can be flexibly changed. The State mode is an object behavior mode.

Ii. Applicable scenarios

It is used to solve the encapsulation problem of complex object state conversion and downlink behavior of different states in the system. Simply put, it is used to process various states of objects and their mutual conversion.

Iii. UML class diagram


4. Participants

1) AbstractState (abstract state class ):

The abstract state class Defines abstract behavior methods in different states, while different behavior operations are implemented in sub-classes (different state subclasses.

2) ConcreteState (a State subclass that implements a specific State downlink ):

A subclass of the abstract state class. each subclass implements a state-related behavior related to the Context class. Each specific state class corresponds to a specific state of the environment, different States have different behaviors.

3) Context (Environment class with State objects ):

It has state attributes. Due to the diversity of environments, it can have different states and behave differently in different States. Maintain an abstract state instance in the Environment class. This instance defines the State (setState () method) of the current environment, and separates specific state behaviors from different state subclasses.

V. Use Case Learning

1. abstract State class: State. java

/*** State mode of JAVA Design Pattern * abstract State class * @ author lvzb.software@qq.com **/public abstract class State {/*** State behavior abstract method, different Behavior logic is implemented by the specific state subclass */public abstract void Behavior ();}

2. Specific state subclass A: ConcreteStateA. java

/*** Specific State subclass A * @ author lvzb.software@qq.com */public class ConcreteStateA extends State {@ Override public void Behavior () {// State A's business Behavior, and what can I do when it is in this status? // For example, if the phone is out of service without overdue payment, it can call the System normally. out. println ("the phone can call normally when the phone is not suspended due to overdue payment ");}}

3. Status subclass B: ConcreteStateB. java

/*** Specific State subclass B * @ author lvzb.software@qq.com **/public class ConcreteStateB extends State {@ Override public void Behavior () {// State B's business Behavior, and what can I do when it is in this status? // For example, if the phone is suspended due to overdue payment, you cannot call System. out. println ("You cannot call a phone number when your phone is out of service due to overdue payment ");}}

4. Environment class with State objects: Context. java

/*** Environment/context class <br/> * State object, and the transition between States can be completed [State change/switch implementation in the Environment class] * @ author lvzb.software@qq.com **/public class Context {// maintain a reference to an abstract State object private State state; /** simulate the phone charge attributes <br/> * Environment Status: * 1>. When bill >=0.00 $: normally, you can call ** 2>. When bill <0.00 $: The phone is in arrears, you cannot call */private double bill;/*** environment processing function, call status instance behavior completion business logic <br/> * Handle different behaviors in different States based on instance references */public void Handle () {checkState (); state. behavior ();}/*** check the environment status: status changes/switches are implemented in the Environment class */private void checkState () {if (bill> = 0.00) {setState (new ConcreteStateA ();} else {setState (new ConcreteStateB () ;}/ *** sets the environment status <br/> * Private method, the purpose is to allow the environment status to be controlled/switched by the system environment. external users do not need to care about the internal status of the Environment * @ param state */private void setState (State state) {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 account balance:" + context. getBill () + "$"); context. handle (); context. setBill (-1.50); System. out. println ("current account balance:" + context. getBill () + "$"); context. handle (); context. setBill (50.00); System. out. println ("current account balance:" + context. getBill () + "$"); context. handle ();}}

6. program running result:

Current Balance: 5.5 $
The mobile phone can call normally when the service is stopped without arrearage
Current Balance:-1.5 $
You cannot call a mobile phone when your phone is out of service.
Current Balance: 50.0 $
The mobile phone can call normally when the service is stopped without arrearage

Vi. Expansion

There are two different implementation methods for status switching in status mode.

Method 1:Status changes/switches are implemented in the environment. The checkState () method in the Context class of the above case code.

/*** Check the environment status: the status changes/switches are implemented in the Environment class */private void checkState () {if (bill> = 0.00) {setState (new ConcreteStateA ();} else {setState (new ConcreteStateB ());}}

Method 2:Status Change/switch is implemented in a specific status subclass.

The implementation steps are as follows:

1) initialize a State instance object in the Context class of the Environment class, and pass the environment Context object as a construction parameter of the subclass state to a specific State subclass instance.

For example, in the Context. java class

// Set the initial state this. state = new ConcreteStateA (this );

2) Check and switch the status based on the constructed context object in the specific subclass status class by calling the attribute value of the context object for business logic judgment.

For example, in the specific state subclass ConcreteStateA. java class:

/*** Specific State subclass A * @ author lvzb.software@qq.com */public class ConcreteStateA extends State {private Context ctx; public ConcreteStateA (Context context) {ctx = context ;} @ Override public void Behavior () {// Business Behavior of status A, and what can I do when it is in this status // For example, if the mobile phone is out of service without overdue payment, the System can call normally. out. println ("the phone can call normally when the phone is not suspended due to overdue payment"); checkState ();} /*** check whether the status needs to be converted <br/> * Status switching is implemented by */private void checkState () {if (ctx. getBill () <0.00) {ctx. setState (new ConcreteStateB (ctx ));}}}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.