State mode--three states of water

Source: Internet
Author: User

State mode--three states of water

What is a state?

A state is a form in which things are located. The state pattern is that when an object changes its internal state, its behavior behaves differently from the external property, and the object looks like it has changed its type. Therefore, the state pattern is also called the object's behavior pattern.

As we often see in the life of water, there are three different states of ice, water, steam, three states of the external nature of the performance is completely different: 1. Ice, hard, non-fluidity, smooth surface; 2. water, with fluidity; 3. Steam, invisible to the naked eye, is present in the air, light in quality. These three state characteristics are not significant differences? It is not like the same material, but the fact is that no matter what state it is in, its Terry composition is the same, it is water molecule (H2O).



Water

Taking water as an example, state mode

Do you remember this picture in the physics Book of Junior High school? There are three states of water: solid, liquid, gas, three states exhibit different characteristics and behaviors, and their transitions are accompanied by thermodynamic phenomena. Now to use the program to simulate the three states of water and mutual transformation, how to achieve it?



Three states of water

We think of the class from the object's point of view, first of all, no matter what state it is always water (H2O), so there will be a water class, and it has three states, we can define three state classes: Solidstate, Liquidstate, gaseousstate , from the three words of Solidstate, liquidstate, gaseousstate we will find that there is a state suffix, so we would like to see if there is some commonality between them, can extract a more abstract class, this class is the status of the class. The relationships between these classes are roughly as follows:



A class diagram relationship between water and state

Ok, we already know about the relationship, then start coding realize it, in the process of implementation continue to improve ...

Water.h:

#ifndef __water_h__#define __water_h__//===============================================================Class State;//===============================================================Class water{ Public:Water(); Water (state* pState,Const string& StrName); ~water (); Public://Change StatusBOOL changestate(state* pState);//Set temperature    voidSettemperature (intNtemperature);//Get temperature    intGettemperature ();//heating up, the amplitude of Nstep rise    voidRisetemperature (intNSTEP);//cooling, Nstep reduced amplitude    voidReducetemperature (intNSTEP);//Get name    stringGetName ();//function of water (efficacy)    voidDoWork ();Private:intM_ntemperature;//Water temperature    stringM_strname;//NameState* m_pstate;//Status};#endif //__water_h__

State.h:

#ifndef __state_h__#define __state_h__//===============================================================Class water;//===============================================================Class state{ Public:Virtual~ State() { }//behavior performed in a certain state, use    Virtual voidDoWork (water* pwater) =0;Virtual stringGetstatename ();protected: State(Const string& StrName):M_strstatename(StrName) {}stringM_strstatename;}; Class Solidstate: Publicstate{ Public:Staticsolidstate*getinstance();Virtual voidDoWork (water* pwater);Private:solidstate(Const string& StrName): State(StrName) { }StaticSolidstate* s_psolidstate; Class cgarbo{ Public:        ~Cgarbo()        {if(solidstate::s_psolidstate! = NULL)            {Delete solidstate::s_psolidstate; }        }    };StaticCgarbo S_carbo;}; Class Liquidstate: Publicstate{ Public:Staticliquidstate*getinstance();Virtual voidDoWork (water* pwater);Private:liquidstate(Const string& StrName): State(StrName) { }StaticLiquidstate* s_pliquidstate; Class cgarbo{ Public:        ~Cgarbo()        {if(liquidstate::s_pliquidstate! = NULL)            {Delete liquidstate::s_pliquidstate; }        }    };StaticCgarbo S_carbo;}; Class Gaseousstate: Publicstate{ Public:Staticgaseousstate*getinstance();Virtual voidDoWork (water* pwater);Private:gaseousstate(Const string& StrName): State(StrName) { }StaticGaseousstate* s_pgaseousstate; Class cgarbo{ Public:        ~Cgarbo()        {if(gaseousstate::s_pgaseousstate! = NULL)            {Delete gaseousstate::s_pgaseousstate; }        }    };StaticCgarbo S_carbo;};#endif //__state_h__

Water.cpp:

#include "stdafx.h"#include "Water.h"#include "State.h"Water::water (): M_pstate (NULL), M_strname ("Water (H2O)") {Settemperature ( -);} Water::water (state* pState,Const string& StrName): M_ntemperature (0), M_pstate (pState), M_strname (strName) {if(M_pstate->getstatename (). Compare ("Solid State") ==0) {m_ntemperature =- -; }Else if(M_pstate->getstatename (). Compare ("LIQUID") ==0) {m_ntemperature = -; }Else if(M_pstate->getstatename (). Compare ("Gaseous") ==0) {m_ntemperature = the; }}water::~water () {}BOOLWater::changestate (state* pState) {if(!pstate) {return false; }if(!m_pstate) {cout<<"Initialize to"<< pstate->getstatename () << Endl; }Else{cout<<"by"<< M_pstate->getstatename () <<"into"<< pstate->getstatename () << Endl; } m_pstate = PState;return true;}voidWater::settemperature (intntemperature) {m_ntemperature = Ntemperature;if(M_ntemperature <=0) {Changestate (solidstate::getinstance ()); }Else if(M_ntemperature >0&& m_ntemperature <= -) {Changestate (liquidstate::getinstance ()); }Else{changestate (Gaseousstate::getinstance ()); }}intWater::gettemperature () {returnM_ntemperature;}voidWater::risetemperature (intNstep) {settemperature (m_ntemperature + nstep);}voidWater::reducetemperature (intNstep) {settemperature (m_ntemperature-nstep);}STD::stringWater::getname () {returnM_strname;}voidWater::D owork () {if(m_pstate) {M_pstate->dowork ( This); }}

State.cpp:

#include "StdAfx.h"#include "State.h"#include "Water.h"stringState:: Getstatename(){returnM_strstatename;}//===============================================================Solidstate*Solidstate:: S_psolidstate = NULL; Liquidstate*Liquidstate:: S_pliquidstate = NULL; Gaseousstate*Gaseousstate:: S_pgaseousstate = NULL;//===============================================================Solidstate*Solidstate:: getinstance(){if(!S_psolidstate) {S_psolidstate= NewSolidstate ("Solid State"); }returnS_psolidstate;}voidSolidstate::D owork(Water*Pwater) {cout<< "I am a high-cold, current body temperature" <<Pwater -Gettemperature ()<< "Celsius,"    << "I am steel, like a cold-blooded, please use me to smash people, hey ..." <<Endl;} Liquidstate*Liquidstate:: getinstance(){if(!S_pliquidstate) {S_pliquidstate= NewLiquidstate ("LIQUID"); }returnS_pliquidstate;}voidLiquidstate::D owork(Water*Pwater) {cout<< "I'm a mild-natured, current body temperature." <<Pwater -Gettemperature ()<< "Celsius,"    << "I can nourish everything, drink I can make you more energetic ..." <<Endl;} Gaseousstate*Gaseousstate:: getinstance(){if(!S_pgaseousstate) {S_pgaseousstate= NewGaseousstate ("Gaseous"); }returnS_pgaseousstate;}voidGaseousstate::D owork(Water*Pwater) {cout<< "My warm personality, current temperature" <<Pwater -Gettemperature ()<< "Celsius,"    << "Flying to the sky is my lifelong dream, in which you will not see my existence, I will reach the realm without me ..." <<Endl;}

Test code:

void Teststatedesign () {Water water;Water. DoWork();Water. Settemperature(-4);Water. DoWork();Water. Risetemperature(8);Water. DoWork();Water. Risetemperature( the);Water. DoWork();Water. Reducetemperature( the);Water. DoWork();}

The results are as follows:

Initialize to liquid
I am gentle, the current temperature of 25 degrees Celsius, I can nourish all things, drink I can make your vitality doubled ...
Changed from liquid to solid
My character is high cold, the current body temperature-4 degrees Celsius, I like steel, imitation as cold-blooded, please use me to smash people, hey ...
Changed from solid to liquid
I am gentle, the current temperature of 4 degrees Celsius, I can nourish all things, drink I can make your vitality doubled ...
Changed from liquid to gaseous
My warm personality, the current temperature of 114 degrees Celsius, flying to the sky is my lifelong dream, in which you will not see my existence,
I will reach the realm without me ...
Changed from gaseous to solid
My character is high cold, the current body temperature-16 degrees Celsius, I like steel, imitation as cold-blooded, please use me to smash people, hey ...

Well, the above procedure has been perfect for us to complete the three states of water and the simulation of its transformation. Let's put together a class diagram structure in the code above, such as:



A class diagram relationship between water and state

Solidstate, Liquidstate, gaseousstate three classes with a singleton mode, because the state only needs an object to be able, these three classes Cgarbo is an inner class, only to release the static object, about the use of Singleton mode, you can refer to the A single instance of life--not single. The changestate in water makes it easy to convert between three states.

Status Mode Summary

From the example above, it should be easy to understand the state mode! In fact, it is simple, its structural relationship is as follows:



State mode structure diagram

Behavior is the behavior of different objects in different states (such as DoWork), changestate is used to change the state of an object, and request is an operational one (such as Risetemperature and Reducetemperature).

Copyright NOTICE: This article for Bo Master original article, without Bo Master permitted not for any commercial use, reproduced please indicate the source.

State mode--three states of water

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.