最近在学习重构,希望众高手不吝赐教
如下两段代码,逻辑上是一样的,就是字符串部分不一样,有没有办法时行重构呢?
- Java code
public String getView(User[] user){ String html = ""; for(int i = 0; i < user.length; i++){ html += html + "<input type='checkbox' value='" + user.getId() + "'/>" + user.getName(); } return html; } /*****华丽的分割线*****/ public String getOtherView(User[] user){ String html=""; html += "<select>"; for(int i = 0; i < user.length; i++){ html += html + "<option value='" + user.getId() + "'>" + user.getName() + "</option>"; } html += "</select>"; return html; }
------解决方案--------------------
"<select>"可以作为一个参数传入: 然后判断该参数是否为空,如果为空,则
public String getOtherView(User[] user,String sel){
String html="";
if (sel!="" )
html += "<select>";
for(int i = 0; i < user.length; i++){
if (sel!="" )
html += html + "<option value='" + user.getId() + "'>" + user.getName() + "</option>";
else
html += html + "<input type='checkbox' value='" + user.getId() + "'/>" + user.getName();
}
if (sel!="" )
html += "</select>";
return html;
}
只能这样了
------解决方案--------------------
有点小问题
- Java code
class ViewUserAsHtml { public static String HTML_TAG_SELECT = "<option value='[userId]'>[userName]</option>"; public static String HTML_TAG_CHECK = "<input type='checkbox' value='[userId]'/>[userName]"; public String getView(User[] users) { return getCommonView(users, "", HTML_TAG_CHECK); } /** ***华丽的分割线**** */ public String getOtherView(User[] users) { return getCommonView(users, "select", HTML_TAG_SELECT); } public String getCommonView(User[] users, String wrapper, String htmlFormatter) { String beginTag = ""; String EndTag = ""; if (wrapper != null && wrapper.equals("")) { beginTag = "<" + wrapper + ">"; EndTag = "</" + wrapper + ">"; } StringBuilder html = new StringBuilder(beginTag); for (User user : users) { String s = htmlFormatter.replaceAll("[userId]", user.getId().toString()); s = s.replaceAll("[userName]", user.getName()); html.append(s); } return html.append(EndTag).toString(); } }