关于重构的一些应用
最近在学习重构,希望众高手不吝赐教
如下两段代码,逻辑上是一样的,就是字符串部分不一样,有没有办法时行重构呢?
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;}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(); }}