#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; }
本文地址:http://com.8s8s.com/it/it24238.htm