【问题标题】:Interface Segregation Principle Problem where one interface inherits two interfaces that share the same parent接口隔离原理 一个接口继承两个共享同一个父接口的问题
【发布时间】:2021-12-29 16:27:44
【问题描述】:

我有一个具有以下类型的应用程序正在设置和使用中。

type CompanyFounder {
    name: string;   
    age: number;
    salary: number;
    sharesHeld: number;
    getReasonStartedCompany: string;
};

type NonExecDirector = {
    name: string;   
    age: number;
    sharesHeld: number;
    string[]: getExternalStuff;
};

我的任务是添加一个新类型:

type Person = {
    name: string;   
    age: number;
};

我想我可以使用接口隔离原则改进代码并减少相关类型上的重复字段。 这是我想出的:

type Person = {
    name: string;   
    age: number;
};

interface Employee extends Person {
    salary: number;
}

interface Director extends Person {
    sharesHeld: number;
}

interface CompanyFounder extends Director, Employee {
    getReasonStartedCompany: string;
}

interface NonExecDirector extends Director {
    string[]: getExternalStuff;
}

但是,我认为我有问题。整个系统的工作方式与更改前一样,但我只是想检查是否真的有办法绕过公司创始人两次收到 nameage 的事实,因为它扩展了 Director 和 Employee。

只是为了让服务器端/后端开发人员参与其中,这是 C# 示例中的相同问题

public interface Person {
    string GetName();   
    int GetAge();
}

public interface Employee : Person {
    int GetSalary();
}

public interface Director : Person {
    int GetSharesHeld();
}

public interface CompanyFounder : Director, Employee {
    string GetReasonStartedCompany();
}

public interface NonExecDirector : Director {
    string[] GetExternalStuff();
}

所以,问题是公司创始人收到了两次GetName()GetAge(),因为它同时实现了 Director 和 Employee。

谁能帮忙解决这个问题?

【问题讨论】:

  • 类型/接口只是一个契约,它没有实现任何东西。这里也没有重复..
  • 我怀疑这是我的理解不足。非常感谢。
  • 其实这是一个复杂的问题。假设公司创始人在员工中被称为 Bill,但在董事列表中显示名称时更喜欢 William。有Employee.GetNameDirector.GetName 的显式实现可能会很好。 C# 允许显式接口实现,但它不允许显式实现接口一回到继承链中。例如,如果员工和主管都声明了GetPicture,那么一个类可以实现Employee.GetPictureDirector.GetPicture,但不能实现Employee.GetAge
  • 顺便说一句,这在上个月的某个时候咬了我——我不记得是什么问题了。解决方案是一个完整的 Kludge
  • @Flydog57 我不确定 TS 是否支持显式接口实现

标签: c# typescript solid-principles interface-segregation-principle


【解决方案1】:

为什么导演不领薪水?董事是雇员,而雇员自然也是人。

public interface Director : Employee {
    int GetSharesHeld();
}

public interface CompanyFounder : Director {
    string GetReasonStartedCompany();
}

【讨论】:

  • 因为非执行董事是董事而不是雇员。接口映射组织结构。与 CompanyFounder 一样,FinanceDirector 将扩展 Director 和 Employee。除此之外,我最近一直在使用 Typescript 中的 Omit 和 Pick,它们实际上以不同的非传统 OOP 方式解决了问题。
猜你喜欢
  • 1970-01-01
  • 2020-12-09
  • 2010-12-13
  • 2021-09-12
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
相关资源
最近更新 更多