mardi 7 janvier 2020

Deal with Object params in Java

I am implementing a Factory design pattern, as part of it I need to define an input method which should accept n number of object params (vargs) which are needs to passed and Rule classes might grow in future.

The caller of the factory at any time should pass different types of objects as input for different rules.

Please suggest what should be the right way to deal with this kind of problem.

public abstract class BusinessRule {

  public abstract void execute();

  /* This method should accept n number of Objects of different type */
  public abstract void input(Object... params);
}  

/* Check Rule accepts Order & Purchase objects as inputs */
public class CheckRule extends Rule {

  @Override
  public void execute() {

  }

  @Override
  public void input(Object... params) {        

  }
 }

 /* ColorRule accepts Paint, Purchase & Sales objects as inputs */
 public class ColorRule extends Rule {

          @Override
          public void execute() {

          }

          @Override
          public void input(Object... params) {           

          }
         }


public class RuleFactory {

  private RuleFactory() {

  }

  public static Rule getRule(String ruleName) {
    if ("CheckRule".equals(ruleName)) {
      return new CheckRule();
    } else if("ColorRule".equals(ruleName)) {
        return new ColorRule();
    }
    return null;

  }
}

The caller gets a rule he wants and pass the params to input method as mentioned in the below code.

Rule rule = RuleFactory.getRule("CheckRule");
        Order order = new Order();
        Purchase purchase = new Purchase();
        rule.input(order,purchase);
        rule.execute();

     Rule rule1 = RuleFactory.getRule("ColorRule");
        Paint paint = new Paint();
        Purchase purchase = new Purchase();
        Sale sale = new Sale();
        rule1.input(paint, purchase, sale);

Aucun commentaire:

Enregistrer un commentaire