Java中不可变和可变对象的设计
我的问题涉及 API 设计。
假设我正在设计一个向量(数学/物理含义)。我希望同时拥有一个不可变的实现和一个可变的实现。
然后我的向量看起来像这样:
public interface Vector {
public float getX(); public float getY();
public X add(Vector v);
public X subtract(Vector v);
public X multiply(Vector v);
public float length();
}
我想知道如何确保同时拥有可变和不可变的实现。我不太喜欢 java.util.List 的方法(默认情况下允许可变性)和 Guava 的不可变实现所具有的 UnsupportedOperationException() 。
如何使用这两种实现来设计“完美”接口或抽象类 Vector?
我考虑过这样的事情:
public interface Vector {
...
public Vector add(Vector v);
...
}
public final class ImmutableVector implements Vector {
...
public ImmutableVector add(Vector v) {
return new ImmutableVector(this.x+v.getX(), this.y+v.getY());
}
...
}
public class MutableVector implements Vector {
...
public MutableVector add(Vector v) {
this.x += v.getX();
this.y += v.getY();
return this;
}
...
}
所以总而言之,我想检查这种方法是否存在明显的设计缺陷,它们是什么以及我应该做什么来修复这些缺陷?
注意:“向量”是更通用用例的示例。为了我的问题,我可以选择重写 List 接口或其他任何东西。请关注更一般的用例。
最终选择,在下面的答案之后,基于乔达时间,正如有人解释但现在编辑的:
/** Basic class, allowing read-only access. */
public abstract class ReadableVector {
public abstract float getX(); public abstract float getY();
public final float length() {
return Vectors.length(this);
}
// equals(Object), toString(), hashCode(), toImmutableVectors(), mutableCopy()
}
/** ImmutableVector, not modifiable implementation */
public final class ImmutableVector extends ReadableVector implements Serializable {
// getters
// guava-like builder methods (copyOf, of, etc.)
}
/** Mutable implementation */
public class Vector extends ReadableVector implements Serializable {
// fields, getters and setters
public void add (ReadableVector v) {/* delegate to Vectors */}
public void subtract(ReadableVector v) {/* delegate to Vectors */}
public void multiply(ReadableVector v) {/* delegate to Vectors */}
}
/** Tool class containing all the logic */
public final class Vectors {
public static ImmutableVector add(ReadableVector v1, ReadableVector v2) {...}
public static void addTo(Vector v1, ReadableVector v2) {...}
...
}
我将 Vector 从接口更改为抽象类,因为基本上向量不应该是其他任何东西。
谢谢大家。
My problem concerns an API design.
Let's say I'm designing a vector (math/physics meaning). I would like to have both an immutable implemenation and a mutable one.
I have then my vector that looks like this:
public interface Vector {
public float getX(); public float getY();
public X add(Vector v);
public X subtract(Vector v);
public X multiply(Vector v);
public float length();
}
I wonder how I can ensure to have both a mutable and an immutable implementation. I don't really like java.util.List's approach (allowing mutability by default) and the UnsupportedOperationException() that Guava's immutable implementation has.
How can I design a "perfect" interface or abstract class Vector with both these implementations?
I've thought about something like this:
public interface Vector {
...
public Vector add(Vector v);
...
}
public final class ImmutableVector implements Vector {
...
public ImmutableVector add(Vector v) {
return new ImmutableVector(this.x+v.getX(), this.y+v.getY());
}
...
}
public class MutableVector implements Vector {
...
public MutableVector add(Vector v) {
this.x += v.getX();
this.y += v.getY();
return this;
}
...
}
So all in all, I would like to check if this approach has flagrant design flaws, which are they and what should I do tho fix these?
Notes: the "vector" stuff is an example of a more general use case. For the sake of my question I could have chosen to rewrite the List interface or anything else. Please focus on the more general use case.
Final choice, after answers below, based on Joda-time as someone explained but now edited:
/** Basic class, allowing read-only access. */
public abstract class ReadableVector {
public abstract float getX(); public abstract float getY();
public final float length() {
return Vectors.length(this);
}
// equals(Object), toString(), hashCode(), toImmutableVectors(), mutableCopy()
}
/** ImmutableVector, not modifiable implementation */
public final class ImmutableVector extends ReadableVector implements Serializable {
// getters
// guava-like builder methods (copyOf, of, etc.)
}
/** Mutable implementation */
public class Vector extends ReadableVector implements Serializable {
// fields, getters and setters
public void add (ReadableVector v) {/* delegate to Vectors */}
public void subtract(ReadableVector v) {/* delegate to Vectors */}
public void multiply(ReadableVector v) {/* delegate to Vectors */}
}
/** Tool class containing all the logic */
public final class Vectors {
public static ImmutableVector add(ReadableVector v1, ReadableVector v2) {...}
public static void addTo(Vector v1, ReadableVector v2) {...}
...
}
I changed Vector from an interface to a abstract class because basically a vector shouldn't be anything else.
Thank you to everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
作为 Vector 库的用户,我不希望有一个修改当前对象的
add
实现和另一个返回新对象的add
实现(同一接口)一。最好有一组明确的不修改当前对象的方法,然后在可变向量中具有修改当前对象的其他方法。
As a user of your Vector library, I would not like to have one
add
implementation which modifies the current Object and anotheradd
implementation (of the same interface) which returns a new one.Better have a clear set of methods which do not modify the current object, and then have additional methods in the mutable vector which do modify the current object.
我不认为你的设计有任何明显的错误。我发现它完全有效。如果我是你,我会考虑以下几件事:
接口向量思考他们的
实现总是可变的。
当然,大部分观点都是有争议的,这些只是我的观点。
I do not think there is anything evidently wrong with your design. I find it perfectly valid. There are few things that I would take into account if I were you:
interface Vector thinking their
implementations are always mutable.
Of course most of this points are arguable, these are just my opinions.
你的想法很好,但还不够完美。
你遗漏了泛型。
您假设算术运算(例如加法和减法)是为您的 Vector 所持有的类型定义的,这可能不是真的。 (泛型可能会对此有所帮助。)
我不知道不可变向量在数学和物理背景下有多大用处。
完美的 API 应该有一个类似的 Matrix 类,因为您需要进行数学和物理的线性代数。
我会查看 Apache 的通用数学库以获取灵感。这是JAMA的继承人。我发现观察比我更好的人的成功设计和实现是一种很好的学习方法。
Your idea is fine, but it's hardly perfect.
You've left out generics.
You assume that arithmetic operations such as addition and subtraction are defined for the types your Vector is holding, which may not be true. (Generics might help with that.)
I don't know how useful an immutable vector is in the context of mathematics and physics.
A perfect API would have an analogous Matrix class, since you'll need to do linear algebra for math and physics.
I'd have a look at Apache's common math library for inspiration. It's the heir to JAMA. I find that looking at successful designs and implementations by my betters is a good way to learn.
我觉得这个设计不太好。拥有可变算术对象并不好,即使您有它们明确标记为可变的。此外,我不会将向量运算放在向量类中。因为现在你只有加法和乘法,明天你会想要别的东西,你的班级会随着你添加这个或什么向量运算而不断成长。如果我是你,我会创建一个像这样的不可变向量
,然后创建一个用于执行基本向量操作的类:
这样,您将有一种简单的方法来扩展系统,而无需触及现有类,也不会引入可变性,这只会使情况变得复杂事物。
更新:
如果您仍然想使用可变向量,那么我会将 SetX 和 SetY 设置器添加到 Vector 类中,但将可变性决策放入 BaseVectorAlgebra 中,如下所示:
但实际上我不喜欢这里的可变性,因为它带来了不必要的并发症
I think this design is not very good. Having mutable arithmetical objects is not good if even you have them explicitly marked as mutable. Additionally, I wouldn't put vector operations in the class vector. Because now you have only addition and multiplication and tomorrow you will want something else and your class will grow and grow as you will add this or what vector operation. If I were you, I would create an immutable vector like this
and then I would create a class for doing basic vector operations:
This way you will have an easy way to extend the system without touching existing classes and without introducing mutability, which just complicate things.
UPDATE:
If you still want to go with mutable vectors, then I would add SetX and SetY setters into Vector class, but put mutability decision into BaseVectorAlgebra like this:
But really I don't like mutability here as it introduces unnecessary complications