帮忙看看这个问题,有关模式的问题,高分相送 以上是一个典型的switch语句,根据不同的operType调用不同方法。不只一处,好几处都碰到这种情况,所以感觉有点烦怎样子去掉它,使代码看起顺眼些?或者去掉的代价是什么 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 用factory模式写个factory来创建preparestatement!或者将创建statement的语句写进一个函数,以后直接调用就行了,何必在每处都这么繁琐的写呢? 用工厂模式去创建不同的preparestatement 用工厂的时候也用到switch,感觉差不多的 public PurchaseInfo[] queryPurchases(int operType, User user) throws X { PurchaseInfo[] purchases = null; Connection connection = null; PreparedStatement find = null; try { connection = getConnection(); String strTemp = ""; switch (operType) { case 1: strTemp = m_findNoCheck; break; case 2: strTemp = m_findNoPass; break; case 3: strTemp = m_findPass; break; case 4: strTemp = m_findComplete; break; } PreparedStatement find = con.prepareStatement(strTemp); find.setString(1,""); ResultSet rs = find.executeQuery(); purchases = getPurchases(rs); } catch (SQLException e) { rollback(connection); } commit(connection); return purchases; } 如果不考虑日后的可扩充性,根本没有必要用工厂模式。 Martin Fowler <<重构(Refactoring)>> 一书里的典型例子Replace Type Code with Class Replace Type Code with State/Strategy Replace Type Code with Subclasses http://www.refactoring.com/catalog/ socket是什么东西,有人告诉我吗 急 java swing 如何实现html的fieldset和legend效果 大数据量arraylist与ehcache缓存的问题 一个小程序(递归) 请教swing 的面板(JPanel)跳转及java全局变量设置问题! JInternalFrame之间的切换(急需) 大哥们帮帮我! 如何用java取得ip地址? 什么是Socket??? 问题求解 断网络和重新拨号 请问properties文件有何作用?
或者将创建statement的语句写进一个函数,以后直接调用就行了,何必在每处都这么繁琐的写呢?
PurchaseInfo[] purchases = null;
Connection connection = null;
PreparedStatement find = null;
try {
connection = getConnection();
String strTemp = "";
switch (operType) {
case 1:
strTemp = m_findNoCheck;
break;
case 2:
strTemp = m_findNoPass;
break;
case 3:
strTemp = m_findPass;
break;
case 4:
strTemp = m_findComplete;
break;
}
PreparedStatement find = con.prepareStatement(strTemp);
find.setString(1,"");
ResultSet rs = find.executeQuery();
purchases = getPurchases(rs);
} catch (SQLException e) {
rollback(connection);
}
commit(connection); return purchases;
}
如果不考虑日后的可扩充性,根本没有必要用工厂模式。
Replace Type Code with State/Strategy
Replace Type Code with Subclasses
http://www.refactoring.com/catalog/