[英]Typescript hide props from super class
I have a class that extends another class. 我有一个扩展另一个类的类。 For example:
例如:
class Store extends BehaviorSubject {
constructor(obj) {
super(obj)
}
}
I also have more classes the extends Store
. 我还有更多类扩展
Store
。 What I need is a way to hide some properties from the BehaviorSubject
superclass, for example, the next()
method. 我需要的是一种从
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();
There is a way to do this? 有办法做到这一点?
No. You can override the method in the subclass to do something else (or nothing) but this is violating the Liskov Substitution principle. 不可以。您可以覆盖子类中的方法来执行其他操作(或者不执行任何操作),但这违反了Liskov Substitution原则。
If your Store class is not a BehaviorSubject, and does not act like one, then extending is not correct. 如果您的Store类不是BehaviorSubject,并且不像一个,则扩展不正确。 A Store should contain a private instance of BehaviorSubject in this case, and if necessary expose some of its methods/properties, by “proxying” them.
在这种情况下,Store应该包含BehaviorSubject的私有实例,并且如果需要,通过“代理”它们来暴露它的一些方法/属性。
You can write something like the code below. 您可以编写类似下面的代码。 There's also no inheritance, which is good.
也没有继承,这很好。 Passing the
Store
object via constructor is a way to implement DIP (dependency inversion principle) . 通过构造函数传递
Store
对象是实现DIP(依赖性反转原则)的一种方法。 It's good on its own, because it decouples classes and also makes StoreWrapper
testable. 它本身很好,因为它解耦了类,也使
StoreWrapper
可测试。
Code 码
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;
}
Usage 用法
const originalStore = ...; // <--- this is your original `Store` object.
const wrappedStore = new StoreWrapper(originalStore);
const value = wrappedStore.getValue();
// ... and so on
Important Notes : 重要说明 :
this._store.next()
is still possible to invoke from within the StoreWrapper
, this code is not violating the LSP . StoreWrapper
调用this._store.next()
,但此代码不违反LSP 。 In other words, it does not break the way inheritance is supposed to be used. StoreWrapper
class very easily, in case it grows and gets some "meat" (logic). StoreWrapper
类,以防它增长并获得一些“肉”(逻辑)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.