Search code examples
javascriptnode.jsclassdesign-patternsmediator

Accessing/Calling a class method from another class in mediator pattern javascript


class Customer {
    constructor(name) {
        this.name = name;
    }
    send(amount, to) {
        new GooglePay().send(amount, this, to);
    }
    receive(amount, from) {
        console.log(`Payment of ${amount} from ${from} to ${this.name} is succesful`);
    }
}

the problem is based on mediator pattern. so above i have defined my customer who can send and receive money. So I have built a class called GooglePay which mediates transaction between customers. Customer have send function through which they can send money, it takes 2 arguments (amount ,to)

The function should actually then invoke or be received by the GooglePay instance which then sends the amount to the receiver after checking if the receiver has registered

class GooglePay {
    constructor() {
        this.customerBase = [];
    }
    register(name) {
        this.customerBase.push(name);
        return this;
    }
    send(amount, from, to) {
        if (this.customerBase.filter(cust => cust === to)) {
            to.receive(amount, from);
        } else {
            console.log('This customer does not exist');
        }
    }
}

Kindly help me out, I'm stuck and I dont understand how i can access methods of other classes from a class.


Solution

  • So i have found the correct solution for my problem, check it out:

    class Customer {
        constructor(name) {
            this.name = name;
            this.googlepay = null;
        }
        send_money(amount, to) {
            this.googlepay.transaction(amount, this, to);
        }
        receive_money(amount, from) {
            console.log(`payment of ${amount} from ${from} to ${this.name} is succesful`);
        }
    }
    
    class GooglePay {
        constructor() {
            this.customer_base = [];
        }
        register_customer(customer_class) {
            this.customer_base.push(customer_class);
            customer_class.googlepay = this;
        }
        transaction(amount, from, to) {
            this.customer_base.filter(cust => {
                if (cust.name === to) {
                    cust.receive_money(amount, from.name);
                }
            });
        }
    }
    

    on close observation you can see a property in my customer class constructor called this.googlepay = null

    That's where the trick lies. Cheerios mate Great solving the puzzle.