强制执行函数调用的顺序? [英] enforce order of function calls?

查看:143
本文介绍了强制执行函数调用的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个抽象基类,我想有一个纯虚方法,它必须由派生类实现,但我想确保派生方法以特定的顺序调用函数,我可以做什么来强制它?

Say I have a abstract base class and I want to have a pure virtual method which must be implemented by the derived class but I want to make sure that the derived method calls functions in a particular order what could I do to enforce it ?

IE

base class
virtual void doABC()=0;
virtual void A()=0;
virtual void B()=0;
virtual void C()=0;


// must call ABC in the correct order 
derived class public base
void doABC();

这只是为了更好地了解如何设计我的类,

This is just so I have a better understanding on how to design my classes to enforce someone to use my class correctly.

推荐答案

实际上有两种方法,取决于你是继承还是参数化。

There are actually two particular ways, depending on whether you go with inheritance or parameterization.

如果您有继承,则是 Template Method 模式:

If you with inheritance, it is the Template Method pattern:

class Base {
public:
    void doit() {
        this->do1();
        this->do2();
    }
private:
    virtual void do1() = 0;
    virtual void do2() = 0;
};

如果你参数化,它是 策略 模式:

And if you go with parameterization, it is the Strategy pattern:

class Strategy {
public:
    virtual void do1() = 0;
    virtual void do2() = 0;
};

void doit(Strategy& s) {
    s.do1();
    s.do2();
}

从网站:


[Coplien,C ++ Report,Mar 96,p88]

Strategy is like Template Method except in its granularity. [Coplien, C++ Report, Mar 96, p88]

模板方法使用继承来改变算法的一部分。 使用委托更改整个算法。 [GoF,p330]

Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm. [GoF, p330]

策略修改个别物件的逻辑。 模板方法修改整个类的逻辑。 [Grand,p383]

Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class. [Grand, p383]

我建议您熟悉一下。

这篇关于强制执行函数调用的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆