Search code examples
javamodel-view-controllercontrollers

how to choose one view out of many in controller ( i don't want if/else because i might have many views)


if ( accountType = "admin" )
        return admin view
if ( accountType = "customer" )
        return customer view
if ( accountType = "user" )
        return user view
if ( accountType = "merketing" )
        return marketing view

and so on .......


Solution

  • Use a map where you register your views with the given key:

    viewsMap.put("admin", admin_view);
    viewsMap.put("customer", customer_view);
    ...
    

    and then, just do:

    View view = viewsMap.get(accountType);
    if (view == null) {
        return error_view;
    }
    return view;