C ++设计模式传递参数的大数大数、参数、模式

2023-09-12 21:17:39 作者:兽性打败理性

我有一个实现了几个逻辑上相关的算法(图论)合理大小的类。约10-15参数是必需的作为输入的算法。这些都不是由算法修改,但用于指导它的操作。首先,我解释通过两种方法实现这一点。我的问题是什么是这样做的(无论是或不是这两个选项之一)的常用方法。

I have a reasonably-sized class that implements several logically-related algorithms (from graph theory). About 10-15 parameters are required as input to the algorithm. These are not modified by the algorithm, but are used to guide the operation of it. First, I explain two options for implementing this. My question is what is a common way to do so (whether it is or isn't one of the two options).

我个人不喜欢将这些值作为参数传递给函数时, N 很大,特别是当我还在开发的算法。

I personally don't like to pass these values as parameters to the function when N is large, especially while I'm still developing the algorithm.

void runAlgorithm(int param1, double param2, ..., bool paramN);

相反,我有一个类算法包含算法,我有一个struct AlgorithmGlobals 包含这些参数。我要么通过这个结构为:

Instead I have a class Algorithm that contains the algorithms, and I have a struct AlgorithmGlobals that contains these parameters. I either pass this struct to:

void runAlgorithm(AlgorithmGlobals const & globals);

或者我加一个公共AlgorithmGlobals实例类:

Or I add a public AlgorithmGlobals instance to the class:

class Algorithm {
public:
    AlgorithmGlobals globals;
    void runAlgorithm();
}

然后在其他地方我会使用这样的:

Then elsewhere I'd use it like this:

int main() {
    Algorithm algorithm;
    algorithm.globals.param1 = 5;
    algorithm.globals.param2 = 7.3;
    ...
    algorithm.globals.paramN = 5;

    algorithm.runAlgorithm();

    return 0;
}

注意的构造 AlgorithmGlobals 定义好的默认值,每个参数所以只能使用非默认值需要指定的参数。

Note that the constructor of AlgorithmGlobals defines good defaults for each of the parameters so only the parameters with non-default values need to be specified.

AlgorithmGlobals 不是私有的,因为他们可以自由修改 runAlgorithm()函数被调用之前。有没有必要保护起来。

AlgorithmGlobals are not made private, because they can be freely modified before the runAlgorithm() function is called. There is no need to "protect" them.

推荐答案

这就是所谓的参数对象 的格局,这是一个好东西。我不喜欢的成员的版本,尤其是称其为XGlobals,并暗示它的共享所有的地方。参数对象的模式,而不是通常涉及创建参数对象的实例,并把它当作参数传递给函数调用。

This is called the "Parameter object" pattern, and it's generally a good thing. I don't like the member version, especially calling it "XGlobals" and implying that it's shared all over the place. The Parameter Object pattern instead generally involves creating an instance of the Parameter Object and passing it as a parameter to a function call.

 
精彩推荐
图片推荐