Last active
August 29, 2015 14:23
-
-
Save OriginUnknown/42742c03956d61012480 to your computer and use it in GitHub Desktop.
JavaScript OOP Design Pattern - Adapter Pattern {Class}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<title>Adapter pattern - Class</title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
/* | |
* * Class Adapter -> implements the ITarget interface AND is a child of the Adapter class. | |
* * Using inheritance over composition, it can now call it's parent's methods [the Adapter] directly | |
*/ | |
//Adaptee - class that the Adapter class will inherit from | |
var PayPal = function () {}; | |
PayPal.prototype.payRecepient = function ( amount ) { | |
var fee = 20; | |
var totalAmt = parseInt( amount ) + fee; | |
return totalAmt; | |
}; | |
//1. Create a child class of the PayPal class. If necessary, you can tweak/override the constructor for this new subclass here | |
var PayPalsChildAdapter = function () {}; | |
//2. Next, make PayPalsChildAdapter inherit from it's parent PayPal class | |
PayPalsChildAdapter.prototype = Object.create( PayPal.prototype ); | |
//3. Implement the "imaginary" ITarget interface into the child class | |
PayPalsChildAdapter.prototype.pay = function ( amt ) { | |
var amount = amt;//optional else you can pass the amt parameter straight to the payRecepient() method | |
var totalAmt = this.payRecepient.call( this, amount );//class adapter - inherited from it's parent, we can call PayPal's payRecepient method direct. | |
this.logger = PaymentStatusLogger(); | |
this.logger.add( "Total amount sent incl $20 handling fee is $" + totalAmt + " using PayPal class adapter pattern services" ); | |
/* | |
* * logger is not made private as we'll need access to it when creating the log method below. | |
*/ | |
}; | |
PayPalsChildAdapter.prototype.log = function () { | |
return this.logger.showLogs(); | |
}; | |
//helper function to print out the outcome of the pay() method | |
function PaymentStatusLogger () { | |
var msg = ""; | |
var addMsg = function ( m ) { | |
msg += m + "\n"; | |
}; | |
var show = function () { | |
return msg; | |
}; | |
return { | |
"add" : addMsg, | |
"showLogs" : show | |
} | |
} | |
//client code | |
var payPalChildAdapter = new PayPalsChildAdapter();//new up the Adapter for the client to use | |
/* | |
* * class adapter pattern in action; despite the use of inheritance, the pay method is invoked the same | |
* * way as the object adapter pattern | |
*/ | |
payPalChildAdapter.pay( 12000 ); | |
//log out the payment status | |
console.log( payPalChildAdapter.log() ); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment