使用泛型时复合模式的可扩展性
The scalability of the composite pattern when generics are used
设想以下类型的对象层次结构:
Group
Person
Address
然后是一些 class 实现:
ImmutableGroup
PeopleyPerson
MonsterPerson
PostalAddress
getZip() :: String
EmailAddress
getDomain() :: String
我们希望允许此 API 的客户端以类型安全的方式使用这些类型。所以客户可能想做:
group.personAt(0).getAddress().getDomain()
他们可以这样做,因为组定义为:
Group<? extends PeopleyPerson<EmailAddress>> group
这意味着组必须定义为:
interface Group<A extends Address,P extends Person<A>>
我们必须让组知道地址,即使它没有出现在其 "runtime" API 中。
我闻到了这个味道。这意味着对类型层次结构的任何进一步添加都要求所有父级也在其泛型声明中表示添加的类型。
有办法解决这个问题吗?
应该够了
interface Group<P extends Person<?>>
然后在组合层次结构中使用具体类型定义实际的组实例:
Group<PeopleyPerson<EmailAddress>> group
这样 API 的使用者将在使用的类型上具有类型安全性,同时保持层次结构中的每个接口(例如组、人、地址)与其直接子级之外的类型不可知。
查看此类实现的示例here
设想以下类型的对象层次结构:
Group
Person
Address
然后是一些 class 实现:
ImmutableGroup
PeopleyPerson
MonsterPerson
PostalAddress
getZip() :: String
EmailAddress
getDomain() :: String
我们希望允许此 API 的客户端以类型安全的方式使用这些类型。所以客户可能想做:
group.personAt(0).getAddress().getDomain()
他们可以这样做,因为组定义为:
Group<? extends PeopleyPerson<EmailAddress>> group
这意味着组必须定义为:
interface Group<A extends Address,P extends Person<A>>
我们必须让组知道地址,即使它没有出现在其 "runtime" API 中。
我闻到了这个味道。这意味着对类型层次结构的任何进一步添加都要求所有父级也在其泛型声明中表示添加的类型。
有办法解决这个问题吗?
应该够了
interface Group<P extends Person<?>>
然后在组合层次结构中使用具体类型定义实际的组实例:
Group<PeopleyPerson<EmailAddress>> group
这样 API 的使用者将在使用的类型上具有类型安全性,同时保持层次结构中的每个接口(例如组、人、地址)与其直接子级之外的类型不可知。
查看此类实现的示例here