Is there a design pattern for a class storing information needed by another class, for example for its construction? [closed]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Is there a design pattern for a class storing information needed by another class, for example for its construction? [closed]



I have classes that depends on various parameters, in particular in their constructor.


class Foo
Foo(int foo, double bar);
// no default constructor
;



When Foo is used from another class, I sometimes need to store intermediate values needed by Foo. This happens when Foo depends on one or several values that are not readily available when the object using Foo is created.


Foo


Foo


Foo


Foo



I can store those values in the client class, but when this class uses several objects like Foo I end up having many parameters that relates to Foo-like objects. Therefore I usually end-up creating a class that holds these parameters and can create an object when all necessary parameters are eventually collected.


Foo


Foo



My question is, is there already a named pattern for this, and what is this name? I don't think Factory is the correct name because the intent of a Factory is different and closely related to inheritance. Or, is this approach wrong, and what would be a superior solution?



Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.





Can you please clarify what you mean and want to achieve? What is "depends on several values". Do you mean having data members?
– Klaus
Aug 10 at 9:53




2 Answers
2



The builder pattern lets you defer the construction of an object over e.g. several method calls. It can also increase the flexibility of how you create objects.



Not everything needs to be a full-blown class and not every problem needs a pattern. You could simply use a


struct FooParams
int foo;
double bar;
;



such that the user can first collect the parameters and then create the instance:


FooParams p;
p.foo = getTheFoo();
p.bar = getTheBar();
Foo f(p);



However, if you have many different constructors this does not scale well and you might want to take a look at the builder pattern as suggested by a different answer.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard