我有一些操作...查看,编辑,结帐等。业务逻辑规定如果文档已经签出,则所有视图都会变为编辑。
有一种简洁的OO方式可以做这样的事情:
class Action
{
public:
Document document;
virtual void execute();
};
class View, Edit, Checkout : public Action;
View::execute()
{
if (document.isCheckedOut)
{
delete this;
this = new Edit;
this->execute();
}
/* execute view */
}
更新:你们怎么看待这个:
class Action
{
public:
static int type;
Document document;
virtual void execute();
static Action* construct(int type, Document document) = 0;
private:
Action();
};
class View, Edit: public Action;
Action* View::construct(Document document)
{
if (document.isCheckedOut)
return new Edit(document);
return new View(document);
}
Action* Edit::construct(Document document)
{
return new Edit(document);
}
void onViewButton(Document document)
{
Action *action = View::construct(document);
action->execute();
delete action;
}
答案 0 :(得分:1)
没有办法像这样重新分配'this'指针。您可以使用智能指针实现通过添加间接层来执行类似的操作。
class action_ptr
{
Action* m_Data;
public:
action_ptr(Action* value)
{
m_Data = value;
}
Action* operator->()
{
if(m_Data->isView() && m_Data->isCheckedOut())
{
delete m_Data;
m_Data = new Edit();
}
return m_Data;
}
};
// usage
action_ptr pAction(new View());
pAction->DoViewStuff();
pAction->Checkout();
pAction->OtherStuff(); // If isCheckedOut returned true, this now magically operates on an Edit instead!
这绝不应该是一个完整的实现,仅仅是一个例子 - 存在内存泄漏和许多缺少的功能。
答案 1 :(得分:0)
我可能会用策略模式来解决这个问题,其中策略具有转换成员函数。沿着这些方向的东西(省略了无趣的代码部分):
struct action_strategy {
virtual ~action_strategy();
virtual action_strategy *convert_strategy(document const &doc);
virtual void execute() = 0;
};
class action { // Hur, hur :D
public:
// construct with heap-allocated strategy
action(action_strategy *strategy);
void execute() {
strategy_.reset(strategy_->convert_strategy(doc_);
strategy_->execute();
}
private:
document doc_;
std::auto_ptr<action_strategy> strategy_;
};
// Default: do nothing
action_strategy *action_strategy::convert_strategy(document const &doc) {
return this;
}
class view : public action_strategy {
// overload as necessary
virtual action_strategy *convert_strategy(document const &doc);
};
action_strategy *view::convert_strategy(document const &doc) {
if(doc.is_checked_out()) {
return new edit();
}
return this;
}