必须调用第一个设计模式

Must Invoke first design pattern

本文关键字:设计模式 第一个 调用      更新时间:2023-10-16

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

我有一个基类,用于存储一般对象并在以后调用它。我希望执行将分为两部分:

  1. 必须具有将始终发生的部分(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 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
    }
};