jeudi 6 février 2020

How to correctly implement strategy design pattern

I'm trying to implement strategy design pattern, and want to know if I do it correctly.

Lets say, I have class FormBuilder which uses strategy from list below to build the form:

  • SimpleFormStrategy
  • ExtendedFormStrategy
  • CustomFormStrategy

So the questions are:

  1. Is it correct to select strategy inside FormBuilder, and not passing strategy from outside?
  2. Doesn't this violates open closed principle? So, if I want to add one more form strategy or to remove an existing one, I have to edit the FormBuilder class.

Draft code example

class Form {
    // Form data here
}

interface IFormStrategy {
    execute(params: object): Form;
}

class SimpleFormStrategy implements IFormStrategy {
    public execute(params: object): Form {
        // Here comes logics for building simple form
        return new Form();
    }
}

class ExtendedFormStrategy implements IFormStrategy {
    public execute(params: object): Form {
        // Here comes logics for building extended form
        return new Form();
    }
}

class CustomFormStrategy implements IFormStrategy {
    public execute(params: object): Form {
        // Here comes logics for building custom form
        return new Form();
    }
}

class FormBuilder {
    public build(params: object): Form {
        let strategy: IFormStrategy;

        // Here comes strategy selection logics based on params

        // If it should be simple form (based on params)
        strategy = new SimpleFormStrategy();
        // If it should be extended form (based on params)
        strategy = new ExtendedFormStrategy();
        // If it should be custom form (based on params)
        strategy = new CustomFormStrategy();

        return strategy.execute(params);
    }
}

Aucun commentaire:

Enregistrer un commentaire