跨两个类的属性的数据结构或设计模式



我正在为平衡投资匹配模型投资组合的计算器。

我开发的类看起来像这样:

export class Portfolio {
    public name: string;
    public risks: Risk[];
}
export class Risk  {
    name: string;
    funds: Fund[];
}
export class Fund {
    shares: number;
    value?: number;
    percent: number;
}

此结构有效,但是Fund[]确实是投资组合的属性,而Fund上的属性称为百分比是风险之间唯一改变的东西。在应用程序中,用户可以在风险之间切换,并查看他们需要买卖的东西,但是当他们这样做时,所有输入都清楚了,因为它们与其他实例绑定在一起。

如果funds从风险转移到投资组合,风险类别如何为每个基金存储一个价值?

export class Portfolio {
    name: string;
    risks: Risk[];
    funds: Fund[];
}
export class Risk  {
    constructor (public name: string, public percents: number[]) {}
}
export class Fund {
    shares: number;
    value?: number;
    percent: number;
}
export class PortfoliosService {
    setPercents(riskName) {
        this.currentRisk = this.currentPortfolio.risks.filter(x => x.name === riskName)[0];
        for (const i in this.currentRisk.percents) {
            this.currentPortfolio.funds[i].percent = this.currentRisk.percents[i];
        }
    }
}

这也有效,问题在于它依赖两个独立阵列的大小相同,并且按照相同的顺序。有什么方法可以将百分比值与基金实例相关联,以便如果它们不匹配,则会被编译器捕获?

您可以将每个数组作为对象数组创建,并为每个对象提供独特的ID。然后可以使用唯一的ID来定位对象,因此您无需担心阵列的长度是否相同。

export class PortfoliosService {
    currentPortfolio: Portfolio;
    createRisks(id, name, percents) {
        const obj = {
            id: id,
            name: name,
            percents: percents
        };
        this.currentPortfolio.risks.push(obj);
    }
    createFund(id, shares, value, percent) {
        const obj = {
            id: id,
            shares: shares,
            value: value,
            percent: percent
        };
        this.currentPortfolio.funds.push(obj);
    }
    // other logic that uses ids instead of array lengths to access array members
}

最新更新