Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Dependency Inversion Principle */
- /* high level modules should not depend on low level modules */
- /* abstractions should not depend on details */
- // make transitions/changes is really hard in high level modules,so we should instead creade intermdiate api that wraps around low level module(f.e. Stripe)
- // Good - we didnt have to change any code inside Shop, because we have payment processor interface, that allowing us to not have to change any of store code
- // all we have to do is create new payment processor, wrapping the API (Paypal, Stripe) we want to use and pass that into the new store()
- /* BAD */
- class Shop {
- constructor(user) {
- //this.stripe = new Stripe(user);
- // payment with paypal impl
- this.paypal = new Paypal()
- this.user = user
- }
- purchaseBike(quantity) {
- //this.stripe.makePayment(200 * quantity * 100)
- // payment with paypal impl
- this.paypal.makePayment(this.user, 200 * quantity)
- }
- purchaseHelmet(quantity) {
- //this.stripe.makePayment(15 * quantity * 100)
- // payment with paypal impl
- this.paypal.makePayment(this.user, 15 * quantity)
- }
- }
- class Stripe {
- constructor(user) {
- this.user = user
- }
- makePayment(amountInCents) {
- console.log(`${this.user} made payment of $${amountInCents / 100} with Stripe`)
- }
- }
- class Paypal {
- makePayment(user, amountInDollars) {
- console.log(`${user} made payment of $${amountInDollars} with Paypal`)
- }
- }
- const shop = new Shop('John')
- shop.purchaseBike(2)
- shop.purchaseHelmet(2)
- /* GOOD */
- class Shop {
- constructor(paymentProcessor) {
- this.paymentProcessor = paymentProcessor;
- }
- purchaseBike(quantity) {
- this.paymentProcessor.pay(200 * quantity)
- }
- purchaseHelmet(quantity) {
- this.paymentProcessor.pay(15 * quantity)
- }
- }
- class StripePaymentProcessor {
- constructor(user) {
- this.stripe = new Stripe(user)
- }
- pay(amountInDollars) {
- this.stripe.makePayment(amountInDollars * 100)
- }
- }
- class PaypalPaymentProcessor {
- constructor(user) {
- this.user = user
- this.paypal = new Paypal()
- }
- pay(amountInDollars) {
- this.paypal.makePayment(this.user, amountInDollars)
- }
- }
- class Stripe {
- constructor(user) {
- this.user = user
- }
- makePayment(amountInCents) {
- console.log(`${this.user} made payment of $${amountInCents / 100} with Stripe`)
- }
- }
- class Paypal {
- makePayment(user, amountInDollars) {
- console.log(`${user} made payment of $${amountInDollars} with Paypal`)
- }
- }
- /* const shop = new Shop(new StripePaymentProcessor("John")) */
- const shop = new Shop(new PaypalPaymentProcessor("John"))
- shop.purchaseBike(2)
- shop.purchaseHelmet(2)
Advertisement
Add Comment
Please, Sign In to add comment