Javascript工厂:组成

时间:2019-02-06 11:12:38

标签: javascript composition

我有一个工厂函数( objectFactory ),我想重用其他工厂(例如,可观察的工厂)。

  1. 所示设计有什么问题?
  2. 如何与在$ value上运行的工厂结合(例如添加增加封装的$ value *.inc(1)的方法)?
const pipe = (...fns) => x => fns.reduce( (prev, func) => func(prev), x);
const compose = (...fn) => obj => pipe(...fn)(obj);
const freeze = o => Object.freeze(o);

const observable = o => {
  const observers = {};
  const keys = () => Object.getOwnPropertySymbols(observers).map(k => observers[k]);
  return {
    ...o,
    subscribe(obj) {
      const id = Symbol();
      observers[id] = obj;
      return { id: id, unsubscribe: this.unsubscribe.bind(this, id) };
    },
    unsubscribe(id) {
      delete observers[id];
    },
    notify(value) {
      keys().forEach(obj => obj.update(value));
    }
  };
};

const loggable = text => o => {
  return {
    ...o,
    log: (...args) => { console.log(text, ...args); }
  };
};

// This is the factory
function objectFactory(value, name = 'my factory') {
  var $value = value;

  return compose(
    observable,
    loggable(name),
    freeze)({
    get: () => $value,
    set: set
  });

  function set(val) {
    $value = val;
    this.log('log the set value', $value);
    this.notify($value);
  }
}

0 个答案:

没有答案