Design patterns in layman's mode-state pattern

Source: Internet
Author: User

Mode motive

In many cases, the behavior of an object depends on one or more dynamically changing properties, which are called states, and such objects are called stateful (stateful) objects, so that the state of an object is removed from a series of predefined values. When an object interacts with an external event, its internal state changes, and the behavior of the system changes accordingly.
In UML, you can use state diagrams to describe changes in the state of an object.

Pattern definition
State pattern: Allows an object to change its behavior when its internal state changes, and the object seems to modify its class. Its alias is a state object (Objects for States), and the state mode is an object-behavioral pattern.
The state pattern:allow a object to the alter its behavior while its internal state changes. The object would appear to the change of its class.
Frequency of Use:medium
UML diagram

Pattern structure
The status mode contains the following roles:
Context: Environment class
State: Abstract Status class
Concretestate: Specific Status class

Pattern Analysis
The state pattern describes the change in the state of the object and how the object behaves differently in each state.
The key to state mode is to introduce an abstract class that specifically represents the state of an object, which we call an abstract state class, and each of the object's specific state classes inherits the class and implements the behavior of different states in different state classes, including transitions between various states.

The role of environment classes and abstract state classes needs to be understood in the state schema structure:
The environment class is actually an object with a state, and the Environment class can sometimes act as the role of the state manager, and you can switch states in the environment class.
The abstract state class can be an abstract class or an interface, and different state classes inherit the different subclasses of the parent class, and the state class is generated because the environment class has multiple states, and also satisfies two conditions: these states often need to switch, in different states, the behavior of the object is different. Therefore, the behavior under different objects can be extracted separately and encapsulated in a specific state class, so that the environment class object can change its behavior when its internal state changes, the object seems to modify its class, but actually because of switching to different specific State class implementation. Because the environment class can be set to any specific state class, it is programmed for the abstract state class, which allows the object of any particular State class to be set to the Environment class when the program is run, allowing the environment class to change the internal state and change the behavior.

Pattern Instances and parsing
Endless overtime when Hugh-Status mode sample code
System structure

Context: Environment class Work.cs

namespacestatepattern{ Public classWork {PrivateState current ;  PublicWork () {//working state initialized to morning work stateCurrent =Newforenoonstate (); }        Private Doublehour;  Public DoubleHour {Get{returnHour;} Set{hour =value;} }        Private BOOLfinish;  Public BOOLtaskfinished {Get{returnfinish;} Set{finish =value;} }         Public voidSetState (state s) { current=s; }         Public voidWriteprogram () {current. Writeprogram ( This); }    }}

State: Abstract Status Class State.cs

namespace statepattern{    // Abstraction State public abstract    class  State    {        publicabstractvoid  Writeprogram (work w);    }}

Concretestate: Specific state class morning work status ForenoonState.cs

usingSystem;namespacestatepattern{//Morning work Status     Public classForenoonstate:state { Public Override voidWriteprogram (work W) {if(W.hour < A) {Console.WriteLine ("Current time: {0} Point of work in the morning, Spirit hundred", W.hour); }            Else            {                //more than 12 points, then into the noon working conditionW.setstate (Newnoonstate ());            W.writeprogram (); }        }    }}

Noon Working Status NoonState.cs

usingSystem;namespacestatepattern{//Noon Working Status     Public classNoonstate:state { Public Override voidWriteprogram (work W) {if(W.hour < -) {Console.WriteLine ("Current time: {0} point hungry, Lunch: sleepy, lunch break. ", W.hour); }            Else            {                //more than 13 points, then into the afternoon work statusW.setstate (Newafternoonstate ());            W.writeprogram (); }        }    }}

PM Working Status AfternoonState.cs

usingSystem;namespacestatepattern{//Afternoon work Status     Public classAfternoonstate:state { Public Override voidWriteprogram (work W) {if(W.hour < -) {Console.WriteLine ("Current time: {0} PM It's a good afternoon, keep trying .", W.hour); }            Else            {                //more than 17 points, then into the evening working StateW.setstate (Neweveningstate ());            W.writeprogram (); }        }    }}

Night working Status EveningState.cs

usingSystem;namespacestatepattern{//Night Work Status     Public classEveningstate:state { Public Override voidWriteprogram (work W) {if(w.taskfinished) {//If the task is complete, go off dutyW.setstate (Newresetstate ());            W.writeprogram (); }            Else            {                if(W.hour < +) {Console.WriteLine ("Current time: {0} overtime Oh, tired", W.hour); }                Else                {                    //more than 21 points, then go to sleep working stateW.setstate (Newsleepingstate ());                W.writeprogram (); }            }        }    }}

Sleep State SleepingState.cs

using System; namespace statepattern{    // sleep State public    class  sleepingstate:state    {        publicoverridevoid  Writeprogram (work W)        {            Console.WriteLine (" Current time: {0} point is gone, asleep ", W.hour);     }}}

Afternoon Rest State ResetState.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacestatepattern{//Afternoon Rest Status     Public classResetstate:state { Public Override voidWriteprogram (work W) {Console.WriteLine ("Current time: {0} point home from work.", W.hour); }    }}

Client: Customer Class

usingSystem;namespacestatepattern{classProgram {Static voidMain (string[] args) {            //Emergency ProjectsWork emergencyprojects =NewWork (); Emergencyprojects.hour=9;            Emergencyprojects.writeprogram (); Emergencyprojects.hour=Ten;            Emergencyprojects.writeprogram (); Emergencyprojects.hour= A;            Emergencyprojects.writeprogram (); Emergencyprojects.hour= -;            Emergencyprojects.writeprogram (); Emergencyprojects.hour= -;            Emergencyprojects.writeprogram (); Emergencyprojects.hour= -; Emergencyprojects.taskfinished=false;            Emergencyprojects.writeprogram (); Emergencyprojects.hour= +;            Emergencyprojects.writeprogram (); Emergencyprojects.hour= A;            Emergencyprojects.writeprogram ();        Console.read (); }    }}

Model Pros and cons
Advantages of State mode
? The transform rule is encapsulated.
? Enumerates the possible states that need to determine the kind of state before enumerating the States.
? Put all the behavior related to a state into a class, and can easily add new state, only need to change the state of the object to change the behavior of the object.
? Allows the state transition logic to be integrated with the state object, rather than a large conditional statement block.
? You can have multiple environment objects share a state object, reducing the number of objects in the system.

Disadvantages of State mode
The use of State mode will inevitably increase the number of system classes and objects.
The structure and implementation of the state pattern are complex, and if used improperly will cause confusion in the program structure and code.
The state mode support for the "open and close principle" is not very good, for the state mode that can toggle the state, adding a new state class needs to modify those responsible for the state transformation of the source code, otherwise cannot switch to the new state, and modify the behavior of a State class also need to modify the corresponding class source code.

Mode applicable environment
You can use the state mode in the following situations:
The behavior of an object depends on its state (property) and can change its related behavior depending on its state.
The code contains a number of conditional statements related to the state of the object, which can cause the maintainability and flexibility of the code to become worse, not easily add and remove states, and enhance the coupling between the customer class and the class library. The behavior of the objects is contained in these conditional statements, and these conditions correspond to the various states of the object.

"Statement and thanks"
This article, on the shoulders of many giants, draws on and cites many other works or writings that others have copyrighted, and is here to thank the former people for their contributions. And at the same time publish the quoted content, the original author or source (some of the content from the Internet can not be traced to the source, deeply regret).

"References"
Design mode-the basis of reusable object-oriented software author: [US] Erich gamma/richard Helm/ralph johnson/john vlissides Translator: Li Yingjun/Ma Xiaoxing/Cai Min/Liu Jianzhong and other machinery industry press
Refactoring-Improving the design of existing code author: Martin Fowler Translator: China Power Press, HOU-jie
"Agile software Development-principles, patterns and practices" Author: Robert C. Martin Tsinghua University Press
"Programmer's path to cultivation-from small to expert" by Andrew hunt/david Thomas Electronics Press
Head First design mode author: Freeman translator: O ' Reilly Taiwan company China Power Press
"Zen of Design Pattern" Author: Qin Xiaobo Machinery Industry Press
MSDN Webcast "C # Object-oriented design mode discussion on" lecturer: Li Jianzhong
Liu wei. design mode. Beijing: Tsinghua University Press, 2011.
Liu wei. Design pattern Training Tutorial. Beijing: Tsinghua University Press, 2012.
"Big Liar design Mode" Author: Geoscience Tsinghua University Press
C # Illustrated Tutorial Author: Solis Translator: Surin/Zhu Ye People's post and telecommunications press
"You must know. NET" Author: Wang Tao
. NET in Project author: Li Tianping Electronics Press
The Microsoft. NET Enterprise Application Architecture Design Author: (US) Esposito and other translators: Chen Lifu
http://www.dofactory.com/Patterns/Patterns.aspx. NET Design Patterns
Http://www.cnblogs.com/zhenyulu Blog Lu Zhenyu
Http://www.cnblogs.com/terrylee Blog Li Huijun
http://www.cnblogs.com/anlyren/Blog Anlyren
Http://www.cnblogs.com/idior Blog Idior
Http://www.cnblogs.com/allenlooplee blog Allen Lee
HTTP://BLOG.CSDN.NET/AI92 Blog ai92
http://www.cnblogs.com/umlonline/Blog Zhang
http://www.cnblogs.com/lovecherry/Blog Lovecherry

Design patterns in layman's mode-state 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.