1. Observer
Lets start with Observer pattern:
the special thing about this pattern is that:
it keep tracking changes on some object, and if changes occurred - it broadcasts the changes the to dependent objects.
Subject
To implement the pattern in javascript we need firstly create a "subject":
let Subject = function() {
let observers = [];
return {
subscribe(ob) {
observers.push(ob)
}
unsubscribe(ob) {
observers.splice(observers.indexOf(ob), 1)
},
notify(ob) {
if(observers.indexOf(ob)===-1) {return;}
observers[observers.indexOf(ob)].notify()
}
}
}
As you can see, subject must contain "subscribe", "unsubscribe", and "notify" methods and store all the "observers" at some inner storage/variableObservers
Next thing - lets create the Observer object/class - the only thing it must have - is a "notify" method (for being notified)
let Observer = function(num){
return { notify: () => console.log(`num ${num} notified`)}
}
Thats it - from now we can create observers, subscribe and notify to observers that subscribed:
let s = new Subject();
let ob1 = new Observer(1)
s.subscribe(ob1);
s.notify(ob1);
s.unsubscribe(ob1);
s.notify(ob1); // will not print, because it unsubscribed
The example of this pattern usage, is "addEventListener" method where we can subscribe to some browser events (like click)
2. Factory
This pattern lets users to create objects ONLY by using "creator" (not directly by using "new" keyword)
let CarCreator = function(modl) {
switch(modl) {
case "zaporojets":
return new Zaporojets(); // only creator can use "new"
break;
case "volga":
return new Volga(); // only creator can use "new"
break;
}
The idea here to simplify the objects instantiation for users - they only need to supply the type of car as a string:
let my= CarCreator("volga");
3. Singelton
The idea of this pattern is NOT to let creation of more than one instance of some object:
Here is one of the ways i can think of - not to let users to use "new" keyword:
var Singelton = (function(){
function someObj() {
return {
name:'vasia'
}
}
// only here you can use the 'new'
return new someObj();
}())
console.log(Singelton.name);// will print "vasia"
console.log(new Singelton);// will cause error
The example of this pattern usage, can be the great old JQuery library - that allows you only to use their "$" object without any "new"s prior to it...