我正在使用打字稿和尖角笔。
我有2个非常相似的服务,但是属性不同:
synchronizedMaps: Map<string, Map<string, MapSynchSettings>> = new Map<string, Map<string, MapSynchSettings>>();
groupDispatchers: Map<string, Subject<SynchMapGroupSubject>> = new Map<string, Subject<SynchMapGroupSubject>> ();
mapDispatchers: Map<string, Subject<SynchMapSubject>> = new Map<string, Subject<SynchMapSubject>> ();
public createNewSynchGroup(id?: string): Observable<SynchMapGroupSubject> {
this.synchronizedMaps.set(id, new Map<string, MapSynchSettings>());
this.groupDispatchers.set(id, new Subject<SynchMapGroupSubject>());
this.mapDispatchers.set(id, new Subject<SynchMapSubject>());
return this.groupDispatchers.get(id).asObservable();
}
和
synchronizedDrawer: Map<string, Map<string, SynchWaypointDrawerSettings>> = new Map<string, Map<string, SynchWaypointDrawerSettings>>();
groupDispatchers: Map<string, Subject<SynchWaypointDrawerGroupSubject>> = new Map<string, Subject<SynchWaypointDrawerGroupSubject>> ();
waypointDispatchers: Map<string, Subject<SynchWaypointSubject>> = new Map<string, Subject<SynchWaypointSubject>> ();
constructor() { }
public createNewSynchGroup(id?: string): Observable<SynchWaypointDrawerGroupSubject> {
this.synchronizedDrawer.set(id, new Map<string, SynchWaypointDrawerSettings>());
this.groupDispatchers.set(id, new Subject<SynchWaypointDrawerGroupSubject>());
this.waypointDispatchers.set(id, new Subject<SynchWaypointSubject>());
return this.groupDispatchers.get(id).asObservable();
}
属性类型和方法的返回值都发生了变化,但是这两个服务的方法实现和逻辑是完全相同的。
我想知道是否有一种方法可以将这两个服务合并为一个服务,或者创建一个父类,我可以仅使用变量类型进行扩展,但是所有名称和逻辑都将保持不变。
谢谢
答案 0 :(得分:2)
一种方法是使用generic class,在其中您要为以后要指定的每种类型使用类型参数:
class GeneralThing<S, G, T> {
synchronized: Map<string, Map<string, S>> = new Map();
groupDispatchers: Map<string, Subject<G>> = new Map();
subjectDispatchers: Map<string, Subject<T>> = new Map();
public createNewSynchGroup(id?: string): Observable<G> {
if (!id) throw new Error("What?!");
this.synchronized.set(id, new Map());
this.groupDispatchers.set(id, new Subject<G>());
this.subjectDispatchers.set(id, new Subject<T>());
return this.groupDispatchers.get(id)!.asObservable();
}
}
在上文中,我将属性名称更改为通用名称(因此仅为synchronized
和subjectDispatchers
),并使用了类型参数S
,G
和T
。
然后您可以将两个服务指定为
GeneralThing<MapSynchSettings, SynchMapGroupSubject, SynchMapSubject>
和
GeneralThing<SynchWaypointDrawerSettings, SynchWaypointDrawerGroupSubject, SynchWaypointSubject>
或者您可以给他们具体的名字,例如
class MapThing extends GeneralThing<
MapSynchSettings,
SynchMapGroupSubject,
SynchMapSubject
> {}
class WaypointDrawerThing extends GeneralThing<
SynchWaypointDrawerSettings,
SynchWaypointDrawerGroupSubject,
SynchWaypointSubject
> {}
希望有所帮助;祝你好运!