Java and design pattern-state pattern

Source: Internet
Author: User

Java and design pattern-state pattern

 

Concept:The state pattern encapsulates the behavior of the studied object in different State objects. Each State object belongs to a subclass of an abstract state class. The intention of the state mode is to change the behavior of an object when its internal state changes, that is, different States correspond to different behaviors. The schematic diagram of the Status mode is as follows:

UML class diagram:Context: can be understood as a control class

State is the Status Interface

ConcreteStateA and ConcreteStateB can be considered as interface implementation, that is, the specific state implementation class.

Use Cases:The object State determines the behavior of the object, and dynamically adjusts the behavior of the object according to the state at run time.

The Code contains complex if else judgments, and these branch judgments are related to the status.

Actual scenarios:(1) You can perform operations only when the TV is on or off.

(2) In the WIFI status, you can connect to the WIFI when the WIFI is on. If the WIFI is off, you cannot perform operations.

(3) logon status, which is commonly used in development. Generally, when you enter the system to perform share forwarding or other operations, you must first determine the user's logon status. If you have logged on, you can perform operations, otherwise, you are prompted to log on.

Scenario 1.

 

First, create a Status Interface (corresponding to the State interface in the UML class diagram ):

Package com. state. demo; public interface TvState {/*** TV Status interface, which provides four methods */void nextChanel (); void preChanel (); void turnUp (); void turnDown ();}

The following two implementation classes (corresponding to ConcreteStateA In the UML class diagram ):

Package com. state. demo; public class PowerOnState implements TvState {/*** the remote control button is valid at startup */@ Overridepublic void nextChanel () {System. out. println ("--------- next channel -----------------------") ;}@ Overridepublic void preChanel () {System. out. println ("--------- previous channel -----------------------") ;}@ Overridepublic void turnUp () {System. out. println ("--------- volume increase -----------------------") ;}@ Overridepublic void turnDown () {System. out. println ("--------- volume reduction -----------------------");}}


Implementation Class 2 (corresponding to ConcreteStateB In the UML class diagram ):

Package com. state. demo; public class PowerOffState implements TvState {/*** all buttons in shutdown state are invalid */@ Overridepublic void nextChanel () {System. out. println ("--------- shutdown status unavailable, please first turn on -----------------------") ;}@ Overridepublic void preChanel () {System. out. println ("--------- the shutdown status is unavailable. Please enable ---------------------") ;}@ Overridepublic void turnUp () {System. out. println ("--------- the shutdown status is unavailable. Please enable ---------------------") ;}@ Overridepublic void turnDown () {System. out. println ("--------- the shutdown status is unavailable. Please turn on the machine -----------------------");}}


Next, the control class (corresponding to the Context in the UML class diagram ):

Package com. state. demo; public class TvController {TvState tvState = null; public void setTvState (TvState tvState) {this. tvState = tvState;}/*** start */public void turnOnTv () {setTvState (new PowerOnState (); System. out. println ("-------- starting ---------------");}/*** shutdown */public void turnOffTv () {setTvState (new PowerOffState (); System. out. println ("-------- shut down ---------------");}/*** next channel */public void nextChanel () {tvState. nextChanel ();} public void preChanel () {tvState. preChanel ();} public void turnUp () {tvState. turnUp ();} public void turnDown () {tvState. turnDown ();}}


Finally, write a test class to test the above Code:

Package com. state. demo; public class TestClass {public static void main (String [] args) {TvController tvController = new TvController (); // create a control class tvController. turnOnTv (); // start tvController first. nextChanel (); tvController. turnDown (); tvController. turnOffTv (); // shut down tvController. turnDown (); // The function is no longer available after Shutdown }}

The running instance is as follows:

There are some minor logic problems here, that is, when the system is started, the user will call the system again for prompt. In this case, we can add the following code to the control class;

Package com. state. demo; public class TvController {private boolean isTvOn = false; TvState tvState = null; public void setTvState (TvState tvState) {this. tvState = tvState;}/*** boot */public void turnOnTv () {if (! IsTvOn) {isTvOn = true; setTvState (new PowerOnState (); System. out. println ("-------- starting ---------------");} else {isTvOn = true; System. out. println ("-------- has been started, do not press ---------------") ;}/ *** shut down */public void turnOffTv () {if (isTvOn) {isTvOn = false; setTvState (new PowerOffState (); System. out. println ("-------- shut down ---------------");} else {isTvOn = false; System. out. println ("------- has been shut down. Do not press ---------------") ;}}/*** next channel */public void nextChanel () {tvState. nextChanel ();} public void preChanel () {tvState. preChanel ();} public void turnUp () {tvState. turnUp ();} public void turnDown () {tvState. turnDown ();}}


Make a boot ID and make a judgment before each method call. Then run the test class again:

Package com. state. demo; public class TestClass {public static void main (String [] args) {TvController tvController = new TvController (); // create a control class tvController. turnOnTv (); // start tvController first. turnOnTv (); // start tvController first. nextChanel (); tvController. turnDown (); tvController. turnOffTv (); // shut down tvController. turnOffTv (); // shut down tvController. turnDown (); // The function is no longer available after Shutdown }}

Run the following command:

Conclusion: The control class holds the system status, but the control class does not directly process the behavior, and the behavior is implemented in the status implementation class;

The user directly operates the control class, interacts directly with the control class, and does not directly operate the status implementation class. In this way, there is a separation of duties, which is conducive to system maintenance.

If you like me, please follow me. Thank you.

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.