Design patterns – Part 5: Adapter pattern
Another quite useful pattern is Adapter pattern. Adapters represent an interface between two different classes. For example imagine being a continental EU citizen travelling to UK. For you to plug in to UK power plug, you need an adapter that will take the interface your connector has and output the interface UK power plug demands.
Definition of Adapter pattern is:
The Adapter pattern converts the interface of a class into an interface the client expects. Adapter lets classes work together even if they couldn’t otherwise due to incompatible interfaces.
So how does this work in practice?
You will mostly need adapters when you will obtain code from someone else. But just for the sake of simplicity, we will look into unlikely scenario, when you will get a code that prints “Hello World!” and write an adaptor that displays “Hello adapters!” in message box using the same interface.
First you need a client class and it’s interface. As we know, interfaces are not implemented in LotusScript. Thus, an abstract class will be used instead. Then we’ll need a client class. Both are pasted below:
Class CHelloWorldInterface Sub printText () End Sub End Class Class CHelloWorld As CHelloWorldInterface Sub printText () Print "Hello World!" End Sub End Class
Now, we need to create our interface that displays “Hello adapters!” in message box.
Class CHelloAdaptersInterface Sub msgboxText () End Sub End Class Class CHelloAdapters As CHelloAdaptersInterface Sub msgboxText () Messagebox "Hello Adapters!" End Sub End Class
All we need now is an adapter.
Class CHelloAdpatersAdapter As CHelloWorldInterface m_helloAdapter As CHelloAdaptersInterface Sub new (helloAdapter As CHelloAdaptersInterface) Set Me.m_helloAdapter = helloAdapter End Sub Sub printText() Call m_helloAdapter.msgboxText() End Sub End Class
And to bind it together, here is an agent that will output both results.
Sub Initialize Dim hw As CHelloWorld Dim ha As CHelloAdapters Dim haa As CHelloWorldInterface Set hw = New CHelloWorld () Set ha = New CHelloAdapters () Set haa = New CHelloAdaptersAdapter (ha) 'test HelloAdapters Call ha.msgboxText() 'test HelloWorld Call testHello (hw) 'test HelloAdaptersAdapter Call testHello (haa) End Sub Sub testHello (hello As CHelloWorldInterface) Call hello.printText() End Sub
Leave a Reply