vendredi 8 janvier 2016

What's the name of this javascript chaining pattern with state saved?

I use often the following chaining pattern who create a new instance when I modify an option. So, I can save a 'state' for my configuration :

Class exemple:

let keys = {
  options: Symbol('options')
};

class ChainingAndState {
  constructor(instance = null) {
    this[keys.options] = {};

    if (instance === null) {
      Object.assign(this[keys.options], {
        option1: 42,
        option2: 43,
        option3: 44
      });
    } else {
      Object.assign(this[keys.options], instance[keys.options]);
    }
  }

  options(options) {
    let instance = new ChainingAndState(this);
    Object.assign(instance[keys.options], options);

    return instance;
  }

  option1(option) {
    return this.options({ option1: option });
  }

  option2(option) {
    return this.options({ option2: option });
  }

  option3(option) {
    return this.options({ option3: option });
  }

  show() {
    alert(`option1: ${this[keys.options].option1} - option2: ${this[keys.options].option2} - option3: ${this[keys.options].option3}`);
    return this;
  }
}

Example of use:

let instance1 = new ChainingAndState().option1(1);
let instance2 = instance1.option2(2);
let instance3 = instance1.option3(3);

instance1.show(); // show: option1: 1 - option2: 43 - option3: 44
instance2.show(); // show: option1: 1 - option2:  2 - option3: 44
instance3.show(); // show: option1: 1 - option2: 43 - option3: 3

I think it's an existing pattern, but I don't know their name. Someone know it ? Thanks !

Aucun commentaire:

Enregistrer un commentaire