samedi 2 juillet 2016

How to use HashMap as builder?

i am trying to run some methods depending on the string parameters arriving me. The idea is to activate and deactive some functions from a list of "Terminals". The class is designed for a Command pattern, "doProcess" will be called in some time

My actual solution is awful, so I think about making a HashMap. For example: map.put("Mail",activateMailsOfTerminals)

But I dont know how to call the functions (activateMailsOfTerminals,deactivate...) dynamically depending on the list of string that comes on the constructor

Thank you very much!

Bad solution:

public class ActionsActivator{

Set<Terminal> terminals = new HashSet<>();
Set<String> activate = new HashSet<>();
Set<String> deactivate = new HashSet<>();

public ActionsActivator(Set<Terminal> filteredTerminals,Set<String> active,Set<String> deactive){
    this.terminals = Map().getInstance().getTerminals;
    this.activate.addAll(activate);
    this.deactivate.addAll(deactivate);
}

public void doProcess(){
    if(hasElement(activate,"Mail")) terminals.forEach(terminal->terminal.activateMails());
    if(hasElement(activate,"Register")) terminals.forEach(terminal->terminal.activateRegisters());

    if(hasElement(deactivate,"Mail")) terminals.forEach(terminal->terminal.deactivateMails());
    if(hasElement(deactivate,"Register")) terminals.forEach(terminal->terminal.deactivateRegisters());
}

private Boolean hasElement(Set<String> list, String element){
    return list.stream().anyMatch(elem->elem.equals(element));
}

Aucun commentaire:

Enregistrer un commentaire