mardi 13 avril 2021

How to provide dependencies of an object without using automatic dependency injection framework

Regarding DI technique I have defined MyClass as below:

public class MyClass {
    
    MyClass(Validator validator, Parser parser, Combiner combiner) {
        ...
    }
}

As you can see MyClass has three dependency, this design is very flexible (and also easy to test) because it allows our clients to provide dependencies of MyClass when they create instances of this class, but in terms of usability using this class is hard for clients because they have to pass all dependencies to it when they want to create instances of this class. Specially it makes sense when they usually use special combination of dependencies. What pattern is the best for this situation how can I have both flexibility and simplicity please consider that I don't want to use automatic dependency injection framework like Spring and I want to achieve it in pure Java. what is the best practice or design pattern to provide both flexibility and convenience for the clients of my API.

Here are two approaches I was thinking about, which one is better? What are other alternatives?

Solution one(using child class):

public class SpecialMyClass extends MyClass {

    public SpecialMyClass() {
        super(new SpecialValidator(), new SpecialParser(), new SpecialCombiner());
    }
}

Solution two(using factory):

public class MyClassFactory {
    
    private MyClassFactory() {}

    public MyClass getSpecialMyClass() {
        return new MyClass(new SpecialValidator(), new SpecialParser(), new SpecialCombiner());
    }
}

Aucun commentaire:

Enregistrer un commentaire