【Excel VBA 】簡単なアダプター(adapter(委譲))もどき

自分なりの解釈で、あまり無理をしない簡単なデザインパターンアダプター(adapter(委譲))もどき

— CMyData.cls(データクラス)

Public Name As String

Public Sub DebugPrint()
    Debug.Print "name=" & Me.Name
End Sub

—  CAdapter.cls(Adapter(委譲)クラス)

Implements CMyData

‘委譲元のクラス
Private m_MyData As CMyData

‘追加項目
Public isMarried As Boolean

Private Sub Class_Initialize()
Set m_MyData = New CMyData
End Sub

Private Sub Class_Terminate()

End Sub

‘委譲元クラス(CMyData)とのインターフェース
Private Sub CMyData_DebugPrint()
    Call Me.DebugPrint
End Sub

Private Property Let CMyData_Name(ByVal RHS As String)
    Me.Name = RHS
End Property

Private Property Get CMyData_Name() As String
     CMyData_Name = Me.Name
End Property

‘インターフェース
Public Property Let Name(ByVal RHS As String)
    ‘CAdapterクラスで名前を変更
    m_MyData.Name = RHS & " that is Using Adapter Class"
End Property

Public Property Get Name() As String
    MyData_Name = m_MyData.Name
End Property

Public Sub DebugPrint()
    m_MyData.DebugPrint
    If Me.isMarried = True Then
        Debug.Print "Sorry, I’m Married"
    End If
End Sub

— MainForTest.bas(使い方の例)

Sub Main()

    ‘委譲元(CMyData)を使う場合
    Dim myData As CMyData
    Set myData = New CMyData
   
    myData.Name = "My Name is myData"
    ‘結果(CMyDataクラス)
    Call myData.DebugPrint
 
    ‘アダプター委譲先(CAdapter)を使う場合
    Dim adapter As CAdapter
     Set adapter = New CAdapter
     adapter.Name = "My Name is myData"
     adapter.isMarried = True
     Call adapter.DebugPrint

End Sub

—結果

name=My Name is myData
name=My Name is myData that is Using Adapter Class
Sorry, I’m Married

「adapter.zip」をダウンロード

コメント

タイトルとURLをコピーしました