在MVP中,将对象(通过界面)暴露给视图是否有效,而不是为每个控件设置单独的属性?
例如,我有一个对象Customer
。
客户类
Private this As TCustomer
Private Type TCustomer
FirstName As String
LastName As String
Email As String
End Type
Public Property Get FirstName() As String
FirstName = this.FirstName
End Property
Public Property Let FirstName(ByVal Value As String)
this.FirstName = Value
End Property
Public Property Get LastName() As String
LastName = this.LastName
End Property
Public Property Let LastName(ByVal Value As String)
this.LastName = Value
End Property
Public Property Get Email() As String
Email = this.Email
End Property
Public Property Let Email(ByVal Value As String)
this.Email = Value
End Property
通过界面公开Customer
对象。
ICustomerView界面
Public Sub UpdateFromCustomer(ByVal Customer As Customer)
End Sub
Public Sub ReadToCustomer(ByVal Customer As Customer)
End Sub
实施界面的表格:
Implements ICustomerView
Private p As Presenter
Private Sub ICustomerView_UpdateFromCustomer(ByVal Customer As Customer)
With Customer
TextFirstName.Value = .FirstName
TextLastName.Value = .LastName
TextEmail.Value = .Email
End With
End Sub
Private Sub ICustomerView_ReadToCustomer(ByVal Customer As Customer)
With Customer
.FirstName = TextFirstName.Value
.LastName = TextLastName.Value
.Email = TextEmail.Value
End With
End Sub
'Example written in Excel
Private Sub UserForm_Initialize()
Set p = New Presenter
Set p.View = Me
p.Find
p.Save
End Sub
Private Sub UserForm_Terminate()
Set p = Nothing
End Sub
演示者类
Private m_view As ICustomerView
Private m_model As Model
Public Property Set View(ByVal obj As ICustomerView)
Set m_view = obj
End Property
Public Sub Find()
Dim cust As Customer
Set cust = m_model.DummyCustomer()
m_view.UpdateFromCustomer cust
End Sub
Public Sub Save()
Dim cust As Customer
Set cust = New Customer
m_view.ReadToCustomer cust
m_model.SaveCustomer cust
End Sub
Private Sub Class_Initialize()
Set m_model = New Model
End Sub
Private Sub Class_Terminate()
Set m_view = Nothing
Set m_model = Nothing
End Sub
最后,一个虚拟模型:
Public Function DummyCustomer() As Customer
Dim obj As Customer
Set obj = New Customer
With obj
.FirstName = "some value 1"
.LastName = "some value 2"
.Email = "some value 3"
End With
Set DummyCustomer = obj
End Function
Public Sub SaveCustomer(ByVal Customer As Customer)
If IsValid(Customer) Then InternalSave Customer
End Sub
Private Function IsValid(obj As Customer) As Boolean
IsValid = Len(obj.FirstName) > 0 And _
Len(obj.LastName) > 0 And _
Len(obj.Email) > 0
End Function
Private Sub InternalSave(Customer As Customer)
Debug.Print Customer.FirstName
Debug.Print Customer.LastName
Debug.Print Customer.Email
End Sub
如果我为视图中的每个控件创建一个带有get / set属性的接口,我将有两个类,具体的Customer
类和具有完全相同属性的ICustomerView
接口。
为避免这种重复,上述方法是否可被视为有效替代方案?