以上是一个典型的switch语句,根据不同的operType调用不同方法。
不只一处,好几处都碰到这种情况,所以感觉有点烦
怎样子去掉它,使代码看起顺眼些?或者去掉的代价是什么

解决方案 »

  1.   

    用factory模式写个factory来创建preparestatement!
    或者将创建statement的语句写进一个函数,以后直接调用就行了,何必在每处都这么繁琐的写呢?
      

  2.   

    用工厂模式去创建不同的preparestatement
      

  3.   

    用工厂的时候也用到switch,感觉差不多的
      

  4.   

    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;
        }
     
    如果不考虑日后的可扩充性,根本没有必要用工厂模式。
      

  5.   

    Martin Fowler <<重构(Refactoring)>> 一书里的典型例子Replace Type Code with Class 
    Replace Type Code with State/Strategy 
    Replace Type Code with Subclasses 
    http://www.refactoring.com/catalog/