7/16/19

3 Design Patterns With Javascript By Example

Hi readers. I decided to list here some 3 design patterns i knew (Or so i think) implemented with Javascript:

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/variable

Observers

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...

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...