Adapter Pattern
The gang of four definition is "Convert the interface of a class into another interface clients expect. Adpater lets the classes work together that couldn't otherwise because of incompatible interfaces". Below is an example that uses a third party payment system, this also uses the Factory design pattern.
A VB example of the Adapter Pattern
' This code would be run at page code behind level
Dim aPayment As IPayment
Dim paymentType As String ' this value would be populated elsewhere
aPayment = PaymentFactory.getPayment(paymentType)
aPayment.takePayment(10.5)
' The payment interface
Public Interface IPayment
Sub takePayment(ByVal Amount As Double)
End Interface
' PayPal Payment class that implements the IPayment Interface
Public Class PayPalPayment
Implements IPayment
Public Sub takePayment(ByVal Amount As Double) Implements IPayment.takePayment
' Code to take payment via PayPal merchant
End Sub
End Class
' Credit Card Payment class that implements the IPayment Interface
Public Class CreditCardPayment
Implements IPayment
Public Sub takePayment(ByVal Amount As Double) Implements IPayment.takePayment
' Code to take payment via a credit card
End Sub
End Class
' Adapter Class to ensure third party code implements IPayment
Public Class ThirdPartyPaymentAdapter
Inherits ThirdPartyPayment
Implements IPayment
Public Sub takePayment(ByVal Amount As Double) Implements IPayment.takePayment
' This methods calls the actual thrid party code.
' If we couldn't inherit we could instantiate the object here or in the
' constructor method.
MyBase.makeTransasction(Amount, False)
End Sub
End Class
' Third Party Payment Class
Public Class ThirdPartyPayment
Public Sub makeTransasction(ByVal amount As Double, ByVal refund As Boolean)
' Third party code...
End Sub
End Class
' Factory Class to return Concrete Payment object
Public Class PaymentFactory
Public Shared Function getPayment(ByVal PaymentType As String) As IPayment
Select Case PaymentType
Case "CreditCard"
Return New CreditCardPayment
Case "PayPal"
Return New PayPalPayment
Case Else
Return New ThirdPartyPaymentAdapter
End Select
End Function
End Class