dimanche 24 février 2019

How to avoid need for User code knowing and instantiating concrete Strategy in Strategy Pattern

Strategy pattern decouples the context code and strategies (or algorithm or policy) being used by it. It has an advantage over 'Template Pattern' as it enables dynamic behavior change and uses composition with delegation to achieve it. Below is such example.

public class Context{
    private Policy policy;

    public void setPolicy(Policy policy){
        this.policy = policy;
    }

    public performTask(){
        policy.apply(); // delegate policy apply to separate class
        this.contextualWOrk();
    }
}

public interface Policy{
    void apply();
}

public class PolicyX{
     public void apply(){
         //Policy X implementation
     }
}

public class PolicyY{
     public void apply(){
         //Policy Y implementation
     }
}

Now the Code using above code

public class User{
    public void init(Context context){
         context.setPolicy(new PolicyX());
         context.performTask();
    }
}

Above we see the user code has to know and supply concrete Policy to Context. We can have 'Factory method pattern' but still in such a case user code will have to know the concrete Factory class. This requires user code to instantiate and know about existence of such concrete implementations.

To prevent this a simple solution can be having a static method taking input as string or enum and using 'switch-case' or multiple 'if-else' statements deciding which class to instantiate and provide the implementation to user code. But again this violates 'OCP' as in case of addition of a new type will require the code to be modified.

How this can be made to follow principles in simple application (I am not sure may be with some configurations Spring and other frameworks solves such issues).

Any hints or key points to solve this in simple application will be helpful.

Aucun commentaire:

Enregistrer un commentaire