After reading and watching some videos on dependency injection I still don't understand how to use it properly without breaking encapsulation.
Note: I read How to use Dependency Injection without breaking encapsulation? but I'm still not 100% sure.
My code is a very simple implementation of thread pool, which contains objects of class Worker
which is a package-private class that I don't want to expose to the outside world (and it's really non of their concern).
My thread pool constructor requires a parameter Worker[] workers
(I don't need a factory since I know in advance exactly how many workers I need).
Since my Worker
class is package-private I thought that the right way to construct the thread factory would be to implement a static factory method in the ThreadPool
class as follows:
public static ThreadPool createThreadPool(int numOfWorkers,
BlockingQueue<Runnable> jobQueue,
ThreadFactory threadFactory) {
Worker workers[] = new Worker[numOfWorkers];
for (int i = 0; i < workers.length; i++) {
workers[i] = new Worker(jobQueue, threadFactory, i);
// worker needs the factory in order to provide itself as Runnable
}
return new ThreadPool(workers, jobQueue);
}
So, is creating all these new objects in the static factory method the right way to hide the Worker
class from other packages, or is there something I'm missing here?