i have a design issue, not complicated actually, but i would like to find an elegant way to solve it. And i thought about this:
Issue:
i have a class A that initialize and keep a collection of B
B is just an interface and must be implemented (so we have classes C,D,E,..).
in constructor A recive a bunch of dataset and must initialize some of B (also lot of different instantiation of same or different class) given each dataset. I would like A to not to know any implementation of B.
I have several working solution, but i was thinking about a kind of “delegate in the constructor”.
eg:
1. for each dataset, ds
2. for each implementation of B, bi
3. try to instantiate bi(ds)
4. if success (means no exception)
5. keep reference
this because the data and calculus i use to check if bi are pretty the same of initialization and being in a performance-critic application i would like to avoid doing that twice or doing it in collection class.
it would be really nice but obviously the problem is line 2…
…as well as the doubt about using exception for something that is not actually an exception. (line 4)
so what should be a pattern that
– let me evaluate data and construct all in one.
– avoid creating several “architectural-classes” i would like to avoid an explosion of classes ( kind of typical when exagerating with following design patterns java-style principles imho ) for such a simple task.
– as fast as possible.
– …is elegant 🙂
Your pseudocode suggests a solution: your use of
biis nothing more than a factory function that takes adatasetas input and returns aB*as output. So, you really just need to takebifrom a collection ofstd::function<B* (dataset)>objects.It would be easy enough to require that these factories are only ‘conditional’ factories: that sometimes they return valid objects, and sometimes they don’t, returning
nullptrinstead. This would let you avoid exceptions, and is more faithful to the intent of your usage.