必须调用第一个设计模式

Must Invoke first design pattern

我正在为我的案例寻找一个优雅的解决方案。我试图找到一种设计模式,为这种情况指定并提供解决方案,但我没有找到。

我有一个基础 class 用于存储一般对象并稍后调用它。 我希望执行分为两部分:

  1. A 必须有总是发生的部分 (do1st())。
  2. 用户定义代码 (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 层次结构中将具有半灵活行为的函数拆分为多个部分,并仅将发生变化的部分设为虚拟:

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
    }
};