2016-08-03 89 views
2

我有這種方法,與工作Npgsql的:代碼重複,相同的功能不同類型

private DataTable GetTableN(string sql, string[] pars) 
    { 
     NpgsqlCommand zapytanie = new NpgsqlCommand(sql, connn, trann); 
     NpgsqlDataAdapter da = new NpgsqlDataAdapter(); 
     DataSet ds = new DataSet(); 
     try 
     { 
      if (pars != null) 
      { 
       for (int i = 0; i < pars.Length; i++) 
       { 
        zapytanie.Parameters.AddWithValue("@param" + i, pars[i]); 
       } 
      } 
      connn.Open(); 
      da.SelectCommand = zapytanie; 
      da.Fill(ds); 
      return ds.Tables[0]; 
     } 
     catch (NpgsqlException e) 
     { 
      throw (new SqlException(e.Message.ToString())); 
     } 
     finally 
     { 
      connn.Close(); 
      zapytanie.Dispose(); 
      da.Dispose(); 
      ds.Dispose(); 
     } 
    } 

現在我需要有完全相同的方法,但使用ODBC代替。我只需要做出這些改變

  1. NpgsqlCommand到ObdcCommand
  2. NpgsqlDataAdapter到OdbcDataAdapter的
  3. NpgsqlException到OdbcException

我如何才能避免重複代碼合併這一點,只有一種方法?

+0

有一個布爾,useODBC什麼的,並相應的代碼? – BugFinder

+0

好的,我如何避免try finally塊的重複? – jankes

+0

雖然我沒有使用NGpgsql命令,但它們看起來不一樣,所以唯一明顯的變化就是捕獲odbcexception ..所以只需添加另一個catch。 – BugFinder

回答

0

你可以試着改變你的方法

private DataTable GetTableN(string sql, string[] pars, DbCommand zapytanie, DbDataAdapter da) 
{ 
    DataSet ds = new DataSet(); 
    try 
    { 
     if (pars != null) 
     { 
      for (int i = 0; i < pars.Length; i++) 
      { 
       zapytanie.Parameters.AddWithValue("@param" + i, pars[i]); 
      } 
     } 
     connn.Open(); 
     da.SelectCommand = zapytanie; 
     da.Fill(ds); 
     return ds.Tables[0]; 
    } 
    catch (DbException e) 
    { 
     throw (new SqlException(e.Message.ToString())); 
    } 
    finally 
    { 
     connn.Close(); 
     zapytanie.Dispose(); 
     da.Dispose(); 
     ds.Dispose(); 
    } 
} 

的簽名或使用某種工廠的

private DataTable GetTableN(string sql, string[] pars, MyFactory factory) 
{ 
    DbCommand zapytanie = factory.CreateCommand(...); 
    DbDataAdapter da = new factory.CreateAdapter(...); 
    ... 
} 

,或者您可以使用繼承爲

public abstract class MyClass 
{ 
    private DataTable GetTableN(string sql, string[] pars) 
    { 
     DbCommand zapytanie = CreateCommand(); 
     DbDataAdapter da = CreateAdapter(); 
     ... 
    } 

    protected abstract DbCommand CreateCommand(); 
    protected abstract DbDataAdapter CreateAdapter(); 
} 

public class OdbcClass : MyClass 
{ 
    protected override DbCommand CreateCommand() 
    { 
     // create for odbc 
    } 

    protected override DbDataAdapter CreateAdapter() 
    { 
     // create for odbc 
    } 
} 

public class PostgrClass : MyClass 
{ 
    protected override DbCommand CreateCommand() 
    { 
     // create for postgr 
    } 

    protected override DbDataAdapter CreateAdapter() 
    { 
     // create for postgr 
    } 
} 
0

我猜工廠模式是當時的出路。謝謝。

相關問題