状态模式产生一个可以改变其类的对象
当发现在大多数或者所有函数中都存在有条件的代码时
这种模式很有用
//: C10:KissingPrincess.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
using namespace std;
class Creature {
bool isFrog;
public:
Creature() : isFrog(true) {}
void greet() {
if(isFrog)
cout << "Ribbet!" << endl;
else
cout << "Darling!" << endl;
}
void kiss() { isFrog = false; }
};
int main() {
Creature creature;
creature.greet();
creature.kiss();
creature.greet();
getchar();
} ///:~
greet()等任何其他所有函数在执行操作前必须测试变量isFrog
这样使代码变得笨拙
特别是在系统中加入额外的状态时情况会更加严重
通过将操作委派给状态对象
情况可以改变
代码得到简化
//: C10:KissingPrincess2.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// The State pattern.
#include <iostream>
#include <string>
using namespace std;
class Creature {
class State {
public:
virtual string response() = 0;
};
class Frog : public State {
public:
string response() { return "Ribbet!"; }
};
class Prince : public State {
public:
string response() { return "Darling!"; }
};
State* state;
public:
Creature() : state(new Frog()) {}
void greet() {
cout << state->response() << endl;
}
void kiss() {
delete state;
state = new Prince();
}
};
int main() {
Creature creature;
creature.greet();
creature.kiss();
creature.greet();
getchar();
} ///:~
输出
Ribbet!
Darling!
这里 实现类设计为嵌套或者私有并不是必须的
但如果能做到
就能参加出更清晰的代码
对状态类的改变将会自动地在所有的代码中进行传播