samedi 14 janvier 2023

How to avoid duplicate code while using Strategy Design Pattern?

I am new to design patterns and thinking about using Strategy design pattern for implementing code in my backend service. However, the Strategies are having duplicate code. I have the following classes:-

class StrategyA implements Strategy {
  private Helperclass1 helperclass1;
  private Helperclass2 helperclass2;
  private Daoclass dao;

  public void execute(Object obj) {
    updatedObj = helperclass1.method(obj);
    updatedObj = helperclass2.method2(updatedObj);
    updatedObj = updateObj(updatedObj);
    dao.update(updatedObj);
  }

  private Object updateObj(Object obj) {
    //update obj & return;
  }
}

class StrategyB implements Strategy {
  private Helperclass1 helperclass1;
  private Helperclass2 helperclass2;
  private Daoclass dao;

  public void execute(Object obj) {
    updatedObj = helperclass1.method(obj);
    updatedObj = helperclass2.method2(updatedObj);
    dao.update(updatedObj);
  }
}

class StrategyC implements Strategy {
  private Helperclass1 helperclass1;
  private Daoclass dao;

  public void execute(Object obj) {
    updatedObj = helperclass1.method(obj);
    dao.update(updatedObj);
  }
}

What should I do to remove duplicate code from Strategy pattern? I am considering not using the design pattern to avoid code duplication. Can anyone suggest a better design pattern for this usecase? I read about some similar situations and found that Command or Template patterns may be considered as an alternative (link:What pattern to use with a Strategy Pattern to avoid duplicate code inside Concrete Strategies?). However I am not sure how I can effectively use these patterns for my use-case.

Aucun commentaire:

Enregistrer un commentaire