I would like your feedback regarding some best practices on design relationship between objects, specially when a singleton object is involved.
Let's imagine I need to simulate a Shop with Customers.
There is only one Shop in my application and a Customer belong only to that Shop.
When the Shop closes I need to notify each Customer.
Below some pseudo code.
In both approaches I consider a Shop as a single object.
In approach 01, I call addCustomer on shop.
In approach 02, I call addCustomer when actually creating a Customer object keeping a reference on Shop in every Customer.
I believe a third approach could be also possible, basically where shop and Customer communicate with events. So for example when creating a Customer, an event is broadcasted, shop listen to that event and add a Customer to itself.
What are your opinions, pro/cons regarding these approaches? I am using JavaScript as language. Thanks in advance for your support.
// 01 approch
var shop = {
customers: [],
addCustomer: function (customer) {
this.customers.push(customer);
},
close: function () {
this.customers.forEach(function (customer) {
customer.goOut();
});
}
};
function Customer(name) {
this.name = name;
this.goOut = function () {
console.log(this.name + ' goes out')
}
}
// set up
shop.addCustomer(new Customer('a'));
shop.addCustomer(new Customer('b'));
shop.addCustomer(new Customer('c'));
shop.close();
console.log('-------------------------');
// 02 approch
var shop2 = {
customers: [],
addCustomer: function (customer) {
this.customers.push(customer);
},
close: function () {
this.customers.forEach(function (customer) {
customer.goOut();
});
this.customers = [];
}
};
function Customer2(name) {
this.shop = shop2;
this.name = name;
this.goOut = function () {
console.log(this.name + ' goes out')
}
this.shop.addCustomer(this); // make sense?
}
new Customer2('d');
new Customer2('e');
new Customer2('f');
shop2.close();