Adapter

 Rate It (2)

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

Revision number 2, Wednesday, March 05, 2008 6:52:00 PM by
This is not the most up to date version of this article. The most recent version can be found here.

Comments

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter