如何在控制器中从众多视图中选择一个(我不想要 if/else,因为我可能有很多视图)


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

等等。

使用地图,在其中使用给定键注册视图:

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

然后,只需执行以下操作:

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

你可以把它放到HashMap中,然后从那里获取它;)

如果要

分离创建代码,请使用简化的工厂:

class ViewFactory {
   public static View createView(String viewName)
   {
        if( viewName = admin )
            return new AdminView();
   }
}

你可以这样做,你的视图实现一个通用接口。

最新更新