Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created August 24, 2021 04:24
Show Gist options
  • Save JarvisTheAvenger/f21d29feb588909988c3acedf740c6c4 to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/f21d29feb588909988c3acedf740c6c4 to your computer and use it in GitHub Desktop.
Adapter pattern
import Foundation
// Adapter design pattern
protocol Payment {
func recievePayment(_ payment: Double)
var totalPayment: Double { get }
}
class NetBanking: Payment {
private var total = 0.0
func recievePayment(_ payment: Double) {
total += payment
}
var totalPayment: Double {
return total
}
}
class UPI: Payment {
private var total = 0.0
func recievePayment(_ payment: Double) {
total += payment
}
var totalPayment: Double {
return total
}
}
let upiPayment = UPI()
upiPayment.recievePayment(1000)
upiPayment.recievePayment(2000)
upiPayment.recievePayment(3000)
let netbankingPayment = NetBanking()
netbankingPayment.recievePayment(1000)
netbankingPayment.recievePayment(2000)
netbankingPayment.recievePayment(3000)
let payments: [Payment] = [upiPayment, netbankingPayment]
var total = 0.0
for payment in payments {
total += payment.totalPayment
}
print(total)
// Third party class which doesn't support Payment protocol
class AmazonPayment {
var payment = 0.0
func paid(_ amount: Double) {
payment += amount
}
func paymentSuccessful() -> Double {
return payment
}
}
let amazonPayment = AmazonPayment()
// This line will give error because AmazonPayment class don't support payment protocol
//let thirdPartypayments: [Payment] = [upiPayment, netbankingPayment, amazonPayment]
// Adapter class - Solution
class AmazonPaymentAdapter: Payment {
private var total = 0.0
func recievePayment(_ payment: Double) {
total += payment
}
var totalPayment: Double {
return total
}
}
let amazonPaymentAdapter = AmazonPaymentAdapter()
amazonPaymentAdapter.recievePayment(100)
let thirdPartypayments: [Payment] = [upiPayment, netbankingPayment, amazonPaymentAdapter]
var totalThirdParty = 0.0
for payment in thirdPartypayments {
totalThirdParty += payment.totalPayment
}
print(totalThirdParty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment