我會讓你的新主持人拿在副主持人構造函數的參數,是這樣的:
class DialogPresenter {
private readonly IDialogView view;
private readonly PersonalInformationPresenter personal;
private readonly FriendsPresenter friends;
private readonly EmploymentHistoryPresenter history;
void DialogPresenter(IDialogView view, PersonalInformationPresenter personal, FriendsPresenter friends, EmploymentHistoryPresenter history) {
this.view = view;
this.personal = personal;
this.friends = friends;
this.history = history;
}
bool Display() {
this.personal.Display();
this.friends.Display();
this.history.Display();
return this.view.Display() == DialogResult.Ok;
}
void Save() {
this.personal.Save();
this.friends.Save();
this.history.Save();
}
}
當然如果您的主持人有他們之間的通用接口,這可以簡化(並使其更加可擴展),像這樣:
class DialogPresenter {
private readonly IDialogView view;
private readonly IPresenters[] presenters;
void DialogPresenter(IDialogView view, IPresenters[] presenters)
{
this.view = view;
this.presenters = presenters;
}
bool Display() {
foreach (var item in this.presenters)
item.Display();
return this.view.Display() == DialogResult.Ok;
}
void Save() {
var validation = new List<string>();
foreach (var item in this.presenters)
validation.AddRange(item.Validate());
if (validation.Count > 0) {
_view.ShowErrors(validation);
return;
}
foreach (var item in this.presenters)
validation.AddRange(item.Save());
}
}
編輯: 調用代碼將是someth荷蘭國際集團這樣的:
void DisplayForm() {
using (var frm = new frmDisplay) {
//or just use DI to get the models etc
var personal = new PersonalInformationPresenter(personalModel, frm.PersonalTab); //some properties to expose your views
var friends = new FriendsPresenter(friendslModel, frm.FriendsTab);
var history = new EmploymentHistoryPresenter(employmentHistoryModel, frm.HistoryTab);
var presenter = new DialogPresenter(frm, personal, friends, history);
if (presenter.Display()) {
presenter.Save();
}
}
}
希望這是一些inpsiration /幫助:)
這確實提供了一些啓發。但是,我有以下問題。 每個演示者的「保存」方法在保存之前進行數據驗證,萬一它失敗*調用view.DisplayValidationErrors()*並顯示msgbox(「郵政編碼丟失」等) 如果我選擇使用代碼你建議用戶將得到一個msg.box的第一個選項卡中的驗證錯誤,一個msg.box的第二個選項卡中的驗證錯誤..但我想所有的驗證錯誤彙總在一個msg.box。 – MadSeb 2010-08-05 19:16:27
我已經更新了我的答案(第二個代碼塊)以顯示我如何處理這個問題 – Pondidum 2010-08-12 06:40:35