Composition of objects

I have a class that acts as a manager and does some work. The servlet that starts when the application server starts up starts this manager. I need to add another class that will do other work, and it needs to coordinate work with the manager. I was thinking of adding a class to the manager as an instance variable. Should I create an instance of a new class (for example, in the constructor) or create an instance of the servlet of the new class and call manager.setNewClass () after creating the manager instance?

+3
source share
3 answers

You have to do the last - he will cancel the manager from his delegate. To properly perform the decoupling, you must create an interface that defines the behavior that the manager expects, and then provide the implementation by inverting the control / dependency injection. This will allow you to test the manager and his working class (I called him a delegate, but he may not be isolated).

EDIT - this answer assumes java because you mentioned the servlet.

You have your own manager class, in it you expect an interface

class Manager {
    Worker worker;

    Manager(Worker worker) {
        this.worker = workder
    }
}

Worker is an interface. It defines behavior, but not implementation

interface Worker {
    public void doesSomething(); //method definition but  no implementation
}

you need to create an implementation

class WorkerImpl implements Worker {
    // must define a doesSomething() implementation
}

The manager just knows that he has a worker. You can provide any class that implements the interface. This is a denouement - the Manager is not associated with any particular implementation, it is associated only with the behavior of the worker.

0

, , ( , setNewClass())... , .

, , . Builder . , ( ), . ( ​​ ).

: . , , . , ( )...

+2

It reminds me of the FFF pattern .

It doesn't matter where you create the instance. Just create wherever it suits you, and if you need it elsewhere, just apply basic refactoring.

If you really need a denouement, try using a tool like Guice , but only if you really need it.

+1
source

Source: https://habr.com/ru/post/1789357/


All Articles