I have a class that acts as a manager and does some work.
A servlet that starts up when the application server starts up instantiates this manager.
I need to add another class that will do other work, and needs to coordinate with the manager.
I was thinking about adding the class to the manager as an instance variable.
Should I have the manager instantiate the new class (like in the constructor), or have the servlet instantiate the new class and call manager.setNewClass() after the manager has been instantiated?
I have a class that acts as a manager and does some work. A
Share
You should do the latter — it decouples the manager from its delegate. To do the decoupling correctly, you should create an interface that defines the behavior the manager expects, and then provide an implementation via inversion of control/dependency injection. This will allow you to test the manager and its worker class (I called it a delegate, but it might not be) in isolation.
EDIT — this answer assumes java because you mentioned servlet.
You have your manager class, in it you expect an interface
Worker is an interface. It defines behavour but not implementation
you now need to create an implementation
The manager just knows it gets some Worker. You can provide any class that implements the interface. This is decoupling — the Manager is not bound to any particular implementation, it is bound only to the behavour of a worker.