【问题标题】:Typescript hide props from super class打字稿隐藏超类的道具
【发布时间】:2018-06-04 19:48:15
【问题描述】:

我有一个类扩展了另一个类。例如:

class Store extends BehaviorSubject {
  constructor(obj) {
     super(obj)
  }
}

我还有更多类扩展Store。 我需要的是一种从BehaviorSubject 超类中隐藏某些属性的方法,例如next() 方法。

class SomeStore extends Store {

}

// I want to hide from this class some methods, properties
// That exists on the BehaviorSubject class. 
const s = new SomeStore();

有办法做到这一点吗?

【问题讨论】:

  • 是的,我只想让商店知道这个道具。
  • 没有“隐藏”这些属性的好方法。我强烈建议重新考虑这种方法。最好不要直接从Store 继承,而是包装到一个专门设计的类中,该类不会暴露Storenext() 以及您想要隐藏的所有其他内容。
  • @Igor 你能举个例子吗?
  • 我知道您已经接受了另一个答案,但如果您愿意,可以查看我的代码变体。

标签: javascript typescript


【解决方案1】:

您可以编写类似于以下代码的内容。也没有继承,这很好。通过构造函数传递Store 对象是实现DIP (dependency inversion principle) 的一种方式。它本身就很好,因为它解耦了类并且还使 StoreWrapper 可测试。

代码

export class StoreWrapper {

  constructor(private _store: Store) { }

  // Expose things that you think are okay to expose...
  getValue = this._store.getValue;
  onCompleted = this._store.onCompleted;
  onError = this._store.onError;
  onNext = this._store.onNext;

  // Anything that is not exposed similar to how it is done above, will be hidden
  // next = this._store.next;

}

用法

const originalStore = ...; // <--- this is your original `Store` object.

const wrappedStore = new StoreWrapper(originalStore);
const value = wrappedStore.getValue();
// ... and so on

重要提示

  • 虽然this._store.next() 仍然可以从StoreWrapper 中调用,但此代码并未违反LSP。换句话说,它不会破坏应该使用继承的方式。
  • 您现在可以非常轻松地测试这个 StoreWrapper 类,以防它长大并获得一些“肉”(逻辑)。

【讨论】:

  • 正是我的想法!
【解决方案2】:

没有。您可以重写子类中的方法来执行其他操作(或不执行任何操作),但这违反了 Liskov 替换原则。

如果您的 Store 类不是一个 BehaviorSubject,并且不像一个,那么扩展是不正确的。在这种情况下,Store 应该包含 BehaviorSubject 的私有实例,并在必要时通过“代理”它们来公开它的一些方法/属性。

【讨论】:

  • 是的,很高兴我不是一个人这样想。
  • 看看我下面的答案,如果我可以为 OP 清理它,请告诉我。希望它与您“代理”方法的愿景一致(我试图完全按照字面意思去做):)。
猜你喜欢
  • 2018-05-24
  • 1970-01-01
  • 2020-12-26
  • 2018-10-26
  • 2018-08-15
  • 1970-01-01
  • 2021-04-30
  • 2018-06-30
  • 2021-03-29
相关资源
最近更新 更多