C++ Design Pattern for Passing a Large Number of Parameters

前端 未结 6 921
小鲜肉
小鲜肉 2020-12-25 13:44

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. Thes

6条回答
  •  轮回少年
    2020-12-25 14:34

    Others have mentioned Parameter Object, but there is also another possibility: using a Builder.

    Builder allows you to omit the parameters whose default values are suitable, thus simplifying your code. This is especially handy if you are going to use your algorithm with several different sets of parameters. OTOH it also allows you to reuse similar sets of parameters (although there is a risk of inadvertent reuse). This (together with method chaining) would allow you to write code such as

    Algorithm.Builder builder;
    
    Algorithm a1 = builder.withParam1(1).withParam3(18).withParam8(999).build();
    ...
    Algorithm a2 = builder.withParam2(7).withParam5(298).withParam7(6).build();
    

提交回复
热议问题