必须调用第一个设计模式
Must Invoke first design pattern
我正在为我的情况寻找一个优雅的解决方案。我试图找到一种指定并为这种情况提供解决方案的设计模式,但我没有找到。
我有一个基类,用于存储一般对象并在以后调用它。我希望执行将分为两部分:
- 必须具有将始终发生的部分(do1st())。
- 用户定义的代码 (do2nd())。
例如:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() = 0;
protected:
void do1st() {//Mandatory code to execute for every InvokeBase type when calling operator()};
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived();
void do2nd() {//User defined code}
void operator()()
{
do1st(); // << How to force this execution?
do2nd();
}
};
void main()
{
InvokeBase *t = new InvokeDerived();
t(); // << here i want the execution order will be do1st and then do2nd.
}
诀窍是我希望do1st将始终执行,我不必从InvokeDerived调用它。我想允许用户从 InvokeBase 继承,并保证在调用 operator() 时将始终调用 do1st。
这是模板方法模式:将类层次结构中具有半灵活行为的函数拆分为多个部分,并仅将更改的函数设为虚拟:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() // this is non-virtual (this is the template method)
{
do1st();
do2nd(); // this resolves to virtual call
}
protected:
void do1st() { /* fixed code here */ };
virtual void do2nd() = 0; // variable part here
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived() = default;
protected:
void do2nd() override
{
// code speciffic to InvokeDerived here
}
};
相关文章:
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 资源管理设计模式
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 用于在回调中调用解析器的设计模式
- 设计帮助 - 为不同类型的消息处理通用接口的设计模式
- 如何仅读取文本文件中的第一个值
- 在这种情况下我应该使用哪种设计模式
- C++中物体改变识别的设计模式?
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 具有多个继承共享一个资源的对象 - 寻找良好的设计模式
- 对于存储另一个类所需信息的类,例如其构造,是否有设计模式?
- 无法在硬件模式下创建 SGX 安全区 - "invalid launch token"即使文档将无效的启动令牌指定为第一个
- 两个附带的类层次结构-一个好的设计模式
- 这是一个设计模式吗?从setters返回
- 设计模式-是否有一个有效的案例可以创建一个立即被销毁且不直接在C++中使用的临时模式
- C++设计模式,用于在另一个类中使用抽象类对象
- 如何将不同的数据结构集成为一个?任何设计模式或经验
- 设计模式-有人能给我一个c++中Singleton的例子吗
- C++策略设计模式,制作一个接口数组