Java API 设计:方法中的窄返回类型

编程入门 行业动态 更新时间:2024-10-27 22:25:32
本文介绍了Java API 设计:方法中的窄返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设我有一个类型族,我在基类型中定义了一组方法:

Suppose I have a type family, I have defined a set of methods in base type:

interface Foo<T> {
   Foo<T> a();
   Foo<T> b();
   ...
}

Bar 扩展 Foo

interface Bar<T> extends Foo<T> {
   Bar<T> a();
   Bar<T> b();
   ...
}

然后 Zee 扩展 Bar

interface Zee<T> extends Bar<T> {
   Zee<T> a();
   Zee<T> b();
   ...
}

当我用不同的装饰器实现这个类型家族时,我发现我经常写一些类似的东西

When I implement this type family with different decorators, I found I constantly write something like

class XBar<T> extends XFoo<T> implements Bar<T> {
   Bar<T> a() {
      return (Bar<T>)super.a();
   }
   Bar<T> b() {
      return (Bar<T>)super.b();
   }
   ...
}

真的很累.我想知道这是 Java API 设计中的正常情况还是我做错了什么,或者有一种聪明的方法可以用一行代码来解决常量类型转换?

It is really tedious. I am wondering is this normal case in Java API design or I did something wrong, or there is sort of smart way to workaround the constant typecast with one line of code?

更新,为了回答您的评论和回复,是的,方法链是我想在这里实现的一件事.顺便说一句,Java8 中的 BaseStream 类型声明是解决这个问题的一个很好的例子.我正在尝试使用这种方法.将在此处更新我的进度.

Updates, To answer your comments and response, yes, method chain is one thing I want to achieve here. BTW looks like the BaseStream type declaration in Java8 is a good example of addressing this problem. I am trying to use that approach. Will update my progress here.

更新 2,当我有多个继承级别时,BaseStream 方法不起作用.参见 Java 继承 Fluent 方法在多级层次结构中的返回类型

Updates 2, The BaseStream approach doesn't work when I have multiple inheritance levels. See Java inherited Fluent method return type in multiple level hierarchies

推荐答案

为什么你的子类需要返回子类类型?

Why do your subclasses need to return the subclass type?

Liskov 替换原则 指出对象可以被子类型替换而不改变任何属性,因此如果如果您正确地编写了类代码,那么您就不需要演员表,特别是如果您只是从 super 返回结果.

The Liskov Substitution Principle states that objects can be replaced by subtypes without altering any properties so if you code your classes correctly, then you don't need the cast especially if you are just returning the result from super.

当您需要在链接期间访问额外的子类方法时,我能想到的唯一一次是方法链接(如 builder 模式)......但这应该很少见.

The only time I can think of that has this problem is method chaining (like builder pattern) when you need to access extra subclass methods during the chaining... But that should be rare.

这篇关于Java API 设计:方法中的窄返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 03:15:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/928453.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   方法   Java   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!