mercredi 3 novembre 2021

Avoid Service locator in strategy design pattern

Take a look on that pseudocode

class A,B,C implements StrategyInterface
{
    private dep;

    constructor(Dep dep) {
        this->dep = dep;    
    }
}

class StrategyResolver
{
    private locator;

    constructor(ServiceLocator locator) {
        this->locator = locator;
    }
    
    public function resolve(data): StrategyInterface
    {
        if ( xxx ) {
            return locator->get(A);
        } else if ( yyy ) {
            return locator->get(B);
        }
        return locator->get(C);
    }
}

As service locator is considered as anti pattern, how to avoid it in this case? A,B,C can have various dependencies, thats why I would like to instantiate it using all benefits of dependency injections. I could albo inject A,B,C as dependencies of StrategyResolver, but what if I have there like 10 strategies. The StrategyResolver dependency list is then too long.

Aucun commentaire:

Enregistrer un commentaire