I have a class that represents a table.
As part of the table class I can get a list of product features.
The product features are an array of strings that are calculated in a method and are dedpendent on the material and width of the table.
class Table {
private width: string;
private material: string
constructor(width, material) {
this.width = width;
this.material = material;
}
public getProductFeatures: string[]{
let features: string[] = [];
if (this.material === "oak") {
if(this.width < 200) features.push("lightweight design");
if(this.width >= 200 && this.width < 400) features.push("premium wood lacquer")
if(this.width >= 400) features.push("reinforced frame")
}
return features;
}
}
As we add more material types and more business logic around the features the getProductFeatures
method will grow to be very large.
Is this a case for using a different design pattern to manage this type of behaviour?
Should I be creating a seperate class something like:
class TableFeatureGenerator {
public static getFeatures(table: Table) {
// business logic in here
}
}
let features = TableFeatureGenerator.getFeatures(table);
Or is something like a strategy pattern a good option here?
interface FeatureGenerator {
getFeatures(): string;
}
class OakTableFeatureGenerator implements FeatureGenerator {
getFeatures(){
// oak business logic here
}
}
class PlasticTableFeatureGenerator implements FeatureGenerator {
getFeatures(){
// plastic business logic here
}
}
class TableFeatureGenerator {
private featureGenerator: FeatureGenerator;
constructor(featureGenerator){
this.featureGenerator = featureGenerator;
}
getFeatures(){
this.featureGenerator.getFeatures()
}
}
let table;
if(material === "oak"){
table = new Table(200, "oak", new TableFeatureGenerator(new OakTableFeatureGenerator))
}
if(material === "plastic"){
table = new Table(200, "plastic", new TableFeatureGenerator(new PlasticTableFeatureGenerator))
}
Any advice on how to structure this scenario would be appreciated.
Aucun commentaire:
Enregistrer un commentaire