为什么 Java 开发人员没有创建一个类 AbstractStringBuilder
并将其重命名为 StringBuilder
?
例如,AbstractStringBuilder
中的方法:
public AbstractStringBuilder append(double d) {
FloatingDecimal.appendTo(d,this);
return this;
}
以及StringBuilder
中的方法:
@Override
public StringBuilder append(double d) {
super.append(d);
return this;
}
我想我们可以在 AbstractStringBuilder
中只保留一个方法,它会正常工作。创建无用的包装器 StringBuilder
有什么意义?
最佳答案
由于 AbstractStringBuilder
不是一个 public class
,如果不问开发人员为什么要写它,只能推测...
猜测
注意StringBuffer
,
A thread-safe, mutable sequence of characters.
是在 1.0 中添加的。 StringBuilder
的 Javadoc 读取
A mutable sequence of characters. This class provides an API compatible with
StringBuffer
, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement forStringBuffer
in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference toStringBuffer
as it will be faster under most implementations.
(强调我的)并在 1.5 中添加。这个想法是这个类在大多数情况下是对 StringBuffer
的改进,但总体上在功能上非常相似(可以相互替代)。正如@immibis 和@MadProgrammer 在评论中指出的那样,在您需要类似功能的情况下,继承的想法可以省去很多麻烦。
我在方法append(String
) 中找到了一个简单的示例。在StringBuilder
中,是
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
在StringBuffer
中是
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
在 AbstractStringBuilder
中是
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
我们看到线程安全和非线程安全版本之间的唯一区别是一些缓存控制(toStringCache
),但它们都在它们的父类(super class)中调用相同的方法,因此重用通过继承编码。
类比
把它想象成您是编写代码的人。您创建了一个 dog
类,其中包含狗的解剖结构(耳朵、尾部、4 条腿......)和与其 Action 相关的方法,如 bark
。 5 年后,您想要创建一个类 cat
来表示一只猫。你会从头开始吗?不,您将创建一个具有耳朵、尾部、4 条腿等结构的抽象类 FourLeggedAnimal
,并使用 makeSound
方法。然后,您将扩展此类并在两个子类中使用所有这些相似之处,必要时覆盖(bark
和 meow
)。
问
What's the point of creating the useless wrapper StringBuilder?
会和别人问你一样
What's the point of creating the useless wrapper Cat?
关于java - 创建 AbstractStringBuilder 和 StringBuilder 有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040067/