2011-11-30 56 views
3

我對存儲庫模式相當陌生,我想正確地做到這一點。我也試圖利用控制反轉(也是新的)。用於訪問文本文件的存儲庫模式

我想確保我正確使用存儲庫模式。

我選擇了這個作爲我的知識庫的基礎接口的例子。

public interface IRepository<T> where T : class 
{ 
    IEnumerable<T> Find(Expression<Func<T, bool>> where); 

    IEnumerable<T> GetAll(); 

    void Create(T p); 

    void Update(T p); 
} 

IPaymentRepository是用於擴展IRepository(雖然我不明白爲什麼我需要這個,如果我有上述查找方法)

public interface IPaymentRepository : IRepository<Payment> 
{ 
} 

PaymentRepository簡單的讀取一個文本文件,並生成一個POCO。

public class PaymentRepository : IPaymentRepository 
{ 
    #region Members 

    private FileInfo paymentFile; 
    private StreamReader reader; 
    private List<Payment> payments; 

    #endregion Members 

    #region Constructors 

    #endregion Constructors 

    /// <summary> 
    /// Initializes a new instance of the <see cref="PaymentRepository"/> class. 
    /// </summary> 
    /// <param name="paymentFile">The payment file.</param> 
    public PaymentRepository(FileInfo paymentFile) 
    { 
     if (!paymentFile.Exists) 
      throw new FileNotFoundException("Could not find the payment file to process."); 

     this.paymentFile = paymentFile; 
    } 

    #region Properties 

    #endregion Properties 

    #region Methods 

    public IEnumerable<Payment> Find(Expression<Func<Payment, bool>> where) 
    { 
     throw new NotImplementedException(); 
    } 

    /// <summary> 
    /// Gets all payments from payment file. 
    /// </summary> 
    /// <returns>Collection of payment objects.</returns> 
    public IEnumerable<Payment> GetAll() 
    { 
     this.reader = new StreamReader(this.paymentFile.FullName); 
     this.payments = new List<Payment>(); 

     while (!reader.EndOfStream) 
     { 
      string line = reader.ReadLine(); 
      Payment payment = new Payment() 
      { 
       AccountNo = line.Substring(0, 11), 
       Amount = double.Parse(line.Substring(11, 10)) 
      }; 

      this.payments.Add(payment); 
     } 

     return this.payments; 
    } 

    public void Create(Payment p) 
    { 
     throw new NotImplementedException(); 
    } 

    public void Update(Payment p) 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion Methods 

我想知道如何實現Find方法。我假設我會調用GetAll併爲存儲庫構建一個內部緩存。例如,我想查找所有支付金額大於50美元的帳戶。

+0

小提示:使用File.ReadAllLines獲取一行字符串[]。 – Bas

+0

我以前沒有用過這種方法。你看到性能增益還是隻有更少的代碼行數? – Novus

回答

1

根據您目前的IRepository簽名,你會實現這樣的:

public IEnumerable<Payment> Find(Expression<Func<Payment, bool>> where) 
{ 
    this.reader = new StreamReader(this.paymentFile.FullName); 
    this.payments = new List<Payment>(); 

    while (!reader.EndOfStream) 
    { 
     string line = reader.ReadLine(); 
     Payment payment = new Payment() 
     { 
      AccountNo = line.Substring(0, 11), 
      Amount = double.Parse(line.Substring(11, 10)) 
     }; 
     if (where(payment) 
     { 
      this.payments.Add(payment); 
     } 
    } 

    return this.payments; 
} 

然而,如果你的系統內存允許的話,你可以在保持緩存列表(從GETALL()),並使用查找()列表。這應該快一個數量級,具體取決於列表的大小。

相關問題