我会让您的新演示者将您的子演示者作为构造函数参数,例如:
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());
}
}
编辑:
调用代码是这样的:
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();
}
}
}
希望这是一些启发/帮助:)