lundi 2 septembre 2019

How to combine builder and factory patterns that allow builder customization

So I have a Builder pattern for creating some types of objects that share the same interface
E.g.

private EmployeeBuilder createEmployee(EmployeeDataSource e) {  
    if(e instanceof Engineer) {
       return new EngineerEmployeeBuilder((EngineerDataSource) e);  
    }  
    else if(e instanceof Manager) {  
       return new ManagerBuilder((ManagerDataSource) e);  
    }  
    else if(e instanceof Salesman) {
       return new SalesmanBuilder((SalesmanDataSource) e);  
    }  
    // etc  
}

So far so good as the calling code can just do something like:

Manager m = createEmployee(ManagerDataSource ds).build();

The problem I have is that it turns out that I need to make some changes to the builder object but I can not do them inside the createEmployee as that is called from places that the change should not happen. E.g. the above snippet could become:

EmployeeBuilder eb = createEmployee(EmployeeDataSource ds);  
if(eb instanceof ManagerBuilder) {
    ((ManagerBuilder)eb).setRoleInc(INC_FOR_ROLE);  
}  
return eb.build();  

This looks like a code smell and would like to avoid it.
Is there a combination of design patterns I could use to enhance the original approach?

Aucun commentaire:

Enregistrer un commentaire