I have a question about best dependency injection techniques with polymorphic classes. I am new to C ++, so please forgive me if this is an obvious question. Let's say I have a Runner class that needs to take two objects: Logger and Worker. Logger is an abstract class with two children, for example FileLogger and SocketLogger. Similarly, a worker is an abstract class with two children, such as ApproximateWorker and CompleteWorker.
The Runner class will be created from main () and will create a Logger and Worker based on a configuration file or something similar. I read a lot in SO and other places, and it seems that the general opinion is to prefer stacked objects and pass them by reference. However, I'm not quite sure how to manage the dynamic creation of objects like this. If I used allocated heaps of objects, I could do something like:
Logger* log;
Worker* worker;
if ( {
log = new FileLogger();
} else {
log = new SocketLogger();
}
if () {
worker = new ApproximateWorker();
} else {
worker = new CompleteWorker();
}
Runner runner = Runner(log, worker);
runner.run();
Since I just keep pointers on the stack, I can handle various cases for Logger and Worker myself. If I use objects related to the stack, the only thing I can think of is to do something like this:
if () {
FileLogger log();
ApproximateWorker worker();
Runner runner = Runner(log, worker);
} else if () {
FileLogger log();
CompleteWorker worker();
Runner runner = Runner(log, worker);
} else if () {
SocketLogger log();
ApproximateWorker worker();
Runner runner = Runner(log, worker);
} else {
SocketLogger log();
CompleteWorker worker();
Runner runner = Runner(log, worker);
}
, , . , - .
- ? (, )?