State的用意在于,允许一个对象在其内部状态改变时改变它的行为;
State模拟Context的相关行为接口, 针对具体的状态, 利用虚函数的机制映射到相应的行为, 从而避免大量的条件语句, 使得代码更加清晰, 并且易于维护;当然这样见带来大量的子类, 维护这些类也是要代价的;
这里我做了一个简单的C++实现, 模拟门的打开关闭状态, 和相关状态下的行为;这里的Context状态的变化我处理为委托State改变, 仿照书本案例状态类采用静态的生成, 使得状态对象成为可以共享的轻量级行为对象;
以下完整的源代码示例, 水平有限, 不知理解正不正确;
#pragma warning(disable: 4530)
#pragma warning(disable: 4786)
#include
#include
using namespace std;
class door_state ;
class door_closed;
class door_opened;
class door
{
string _name;
door_state * _state;
friend class door_state;
public:
door(char *name) ;
string & name();
void open();
void close();
void pass();
void report_state();
void change_state(door_state* new_state);
} ;
class door_state
{
public:
virtual void open(door *) = 0; //这里模拟door与状态相关的行为
virtual void close(door *) = 0;
virtual void pass(door *) = 0;
virtual void report_state(door *) = 0;
};
class door_opened : public door_state
{
public:
static door_state* instance() //产生一个全局实例, 这是个轻量级的行为对象, 可以共享
{
static door_opened g_obj;
return &g_obj;
}
virtual void open(door *p) ;
virtual void close(door *p) ;
virtual void pass(door *);
virtual void report_state(door *p);
};
class door_closed : public door_state
{
public:
static door_state* instance()
{
static door_closed g_obj;
return &g_obj;
}
virtual void open(door *p);
virtual void close(door *p);
virtual void pass(door *);
virtual void report_state(door *p);
};
void door_opened::open(door *p)
{
cout << p->name().c_str() << " 已经是打开的" << endl;
}
void door_opened::close(door *p)
{
p->change_state(door_closed::instance());
cout << p->name().c_str() << " 关闭" << endl;
}
void door_opened::pass(door *p)
{
cout << "你可以通过 " << p->name().c_str() << endl;
}
void door_opened::report_state(door *p)
{
cout << p->name().c_str() << " 是打开的" << endl;
}
void door_closed::open(door *p)
{
p->change_state(door_opened::instance());
cout << p->name().c_str() << " 打开" << endl;
}
void door_closed::close(door *p)
{
cout << p->name().c_str() << " 已经是关闭的" << endl;
}
void door_closed::pass(door *p)
{
cout << "门已关闭,你不可以通过 " << p->name().c_str() << endl;
}
void door_closed::report_state(door *p)
{
cout << p->name().c_str() << " 是关闭的" << endl;
}
door::door(char *name) : _name(name)
{
change_state(door_closed::instance());
}
string & door::name()
{
return _name;
}
void door::open()
{
_state->open(this);
}
void door::close()
{
_state->close(this);
}
void door::pass()
{
_state->pass(this);
}
void door::report_state()
{
_state->report_state(this);
}
void door::change_state(door_state* new_state)
{
_state = new_state;
}
int main(int argc, char *argv[])
{
try
{
door d1("door 1#"); //这里可以看到它们的行为随状态而改变
door d2("door 2#"); //同时也可以看到2个对象共享同一个状态对象
d1.report_state();
d1.open();
d2.open();
d1.close();
d1.close();
d1.report_state();
d2.report_state();
d1.pass();
d2.pass();
}
catch(exception &e)
{
cout << e.what() << endl;
}
return 0;
}