Seeking guidance on the implementation of the strategy design pattern to ensure correctness.
Consider a scenario where the class FormBuilder
employs strategies from the following list in order to construct the form:
SimpleFormStrategy
ExtendedFormStrategy
CustomFormStrategy
The questions at hand are:
- Is it appropriate to select the strategy within the
FormBuilder
instead of passing it from an external source? - Does this approach potentially violate the open-closed principle? Meaning, if a new form strategy needs to be added or an existing one removed, would it require modifications in the
FormBuilder
class?
Draft code snippet provided below:
class Form {
// Form data here
}
interface IFormStrategy {
execute(params: object): Form;
}
class SimpleFormStrategy implements IFormStrategy {
public execute(params: object): Form {
// Logic for building simple form goes here
return new Form();
}
}
class ExtendedFormStrategy implements IFormStrategy {
public execute(params: object): Form {
// Logic for building extended form goes here
return new Form();
}
}
class CustomFormStrategy implements IFormStrategy {
public execute(params: object): Form {
// Logic for building custom form goes here
return new Form();
}
}
class FormBuilder {
public build(params: object): Form {
let strategy: IFormStrategy;
// Strategy selection logic based on params goes here
// If it should be a simple form (based on params)
strategy = new SimpleFormStrategy();
// If it should be an extended form (based on params)
strategy = new ExtendedFormStrategy();
// If it should be a custom form (based on params)
strategy = new CustomFormStrategy();
return strategy.execute(params);
}
}