我一直在關注MVVM模式上的Josh Smith的excellent article。在他的榜樣,他有一個CustomerRepository
從源獲取數據:爲什麼庫類會調用靜態加載方法?
public CustomerRepository(string customerDataFile)
{
_customers = LoadCustomers(customerDataFile);
}
我不明白的是,他所謂的靜態方法,LoadCustomers
,直接從他的構造函數的事實:
static List<Customer> LoadCustomers(string customerDataFile)
{
// In a real application, the data would come from an external source,
// but for this demo let's keep things simple and use a resource file.
using (Stream stream = GetResourceStream(customerDataFile))
using (XmlReader xmlRdr = new XmlTextReader(stream))
return
(from customerElem in XDocument.Load(xmlRdr).Element("customers").Elements("customer")
select Customer.CreateCustomer(
(double)customerElem.Attribute("totalSales"),
(string)customerElem.Attribute("firstName"),
(string)customerElem.Attribute("lastName"),
(bool)customerElem.Attribute("isCompany"),
(string)customerElem.Attribute("email")
)).ToList();
}
這是一種延遲加載模式,還是有開發人員會這樣做的其他特定原因嗎?
對我來說似乎是加載測試數據。 –
您很可能會通過依賴注入將您的資源庫注入ViewModel,並在適當的時間使用它來加載數據。就像邁克爾說的那樣,它看起來像一個簡單的方式來獲得一些數據的例子,並不一定反映生產代碼片段。一個倉庫通常是一個singleton(通過容器),因爲它可能是線程安全的,並且不需要多個實例,所以容器負責處理這個問題。靜態方法調用模仿這種類型的設置,而不需要進入依賴注入細節的示例。 – Charleh
@Charleh - 到目前爲止,您的評論對我來說最有意義。因此,想法是將靜態調用隔離到數據源的調用,以避免在存在多個存儲庫實例時重新打開連接。對? – Heliac