我有一个 MVP 的实现,用于域模型中的项目列表。
我的问题通常是如何(或我可以)摆脱具体 View 和 Presenter 中类型参数的重复?
我倾向于认为我遇到了限制,必须忍受重复或重新设计课程。另一种选择是我遗漏了一些明显的东西。无论如何,这就是我在这里问的原因。
具体来说,如果您有:
interface IA<T2, T3> { }
class C<T1, T2, T3> where T1 : IA<T2, T3>
我可以通过编译来推断类型参数 T2 和 T3,结果如下:
interface IB : IA<int, string>
class D : C<IB> { } // can't do this
这编译。重复的参数是Note, string
和Attachment, string
。
// Abstract View
public interface IView<TItem, TKey>
{
void Fill(TItem[] items);
event SelectEvent<TKey> SelectionChanged;
event MessageEvent Add;
}
// Event Delegates
public delegate void SelectEvent<TKey>(TKey selectedValue);
public delegate bool MessageEvent();
// Model Entities
public class Note { }
public class Attachment { }
// Abstract Presenter
public abstract class Presenter<TView, TItem, TKey> where TView : IView<TItem, TKey>
{
protected TKey SelectedValue { get; private set; }
protected TView View { get; set; }
public Presenter(TView view)
{
View = (TView)view;
View.SelectionChanged += OnSelectionChangedInternal;
View.Add += OnAdd;
}
void OnSelectionChangedInternal(TKey selectedValue) {
this.SelectedValue = selectedValue;
OnSelectionChanged(selectedValue);
}
protected abstract void OnSelectionChanged(TKey selectedVaule);
protected abstract bool OnAdd();
}
// Concrete Views
public interface INotes : IView<Note, string> { }
public interface IAttachments : IView<Attachment, string> { }
// Concrete Presenters
public class NotesPresenter : Presenter<INotes, Note, string> {
public NotesPresenter(INotes view) : base(view) { }
protected override void OnSelectionChanged(string publisherName) { }
protected override bool OnAdd() { return false; }
}
public class AttachmentsPresenter : Presenter<IAttachments, Attachment, string> {
public AttachmentsPresenter(IAttachments view) : base(view) { }
protected override void OnSelectionChanged(string publisherName) { }
protected override bool OnAdd() { return false; }
}