状态模式

一、简介

1、状态模式中当一个对象的内部状态改变时允许改变其行为,这个对象看起来像是改变了其类。

2、状态模式可以消化较大的分支,将每个分支放入一种状态中,减少了分支之间的耦合程度,又符合开闭原则。当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式。

3、UML

4、所属类别:行为型

二、C++程序

 1 // 状态模式.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<iostream>
 6 using namespace std;
 7 
 8 
 9 class State
10 {
11 public:
12     State(){}
13     virtual ~State(){}
14     virtual void doit()=0;
15 };
16 
17 
18 class Havebreakfast:public State
19 {
20 private:
21     State *current_state;
22 public:
23     Havebreakfast(){}
24     virtual ~Havebreakfast(){}
25     virtual void doit()
26     {
27         cout<<"吃早饭"<<endl;
28         //current_state=new Havebreakfast();
29         //current_state->doit();
30     }
31 };
32 class Wash:public State
33 {
34 private:
35     State *current_state;
36 public:
37     Wash(){}
38     virtual ~Wash(){}
39     virtual void doit()
40     {
41         cout<<"洗漱"<<endl;
42         current_state=new Havebreakfast();
43         current_state->doit();
44     }
45 };
46 class Getup:public State
47 {
48 private:
49     State *current_state;
50 public:
51     Getup(){}
52     virtual ~Getup(){}
53     virtual void doit()
54     {
55         cout<<"起床"<<endl;
56         current_state=new Wash();
57         current_state->doit();
58     }
59 };
60 class Morning
61 {
62 private:
63     State * current_state;
64 public:
65     Morning()
66     {
67         current_state=new Getup();
68     }
69     ~Morning(){};
70     void doit()

71     {
72         current_state->doit();
73     }
74 };
75 
76 int _tmain(int argc, _TCHAR* argv[])
77 {
78     Morning *m=new Morning();
79     m->doit();
80     return 0;
81 }
原文地址:https://www.cnblogs.com/bewolf/p/4235428.html