我有一些不同类型的操作数,并且想要定义这些操作数如何相互操作。这看起来像一个普通的 问题,但我没有找到一个好的方法来实现它。如何定义java中不同对象之间的通用操作?
说一开始我有标量(即数字),矩阵,并将矩阵或标量的 和我想确定这些加操作:
scalar1.plus(scalar2 )返回标等于scalar1 + scalar2,
matrix.plus(scalar1)或scalar.plus(基体)都返回其中“scalar1”各自元件已经被添加到所述 矩阵的每个元素的矩阵 ,
matrixSet.plus(矩阵)返回一组,每个矩阵已经 添加到矩阵1
等等......请注意,某些操作可能会抛出异常,如 加入不同大小的矩阵或者添加不具有相同数量元素的集合。
我的目标如下:
1-重用的代码量可能(非常重要,因为我将有很多 更多的操作和数据类型),
2-在编译时做尽可能多的验证尽可能
3-可以很容易地在将来添加新的数据类型或操作( 例如,我可能希望再添加的矢量数据类型)
我最初吨hought我将定义一个操作数接口,我的 标量,矩阵和这些元素的集合将实现,并且其 将包括类似的方法:
public Operand plus(Operand op);
这将允许为从底部限定的加操作起来, 开始用最简单的元件(标量):
public Operand plus(Operand operand) {
if (Scalar.class.equals(operand.getClass())) {
return new Scalar(this.value + ((Scalar) operand).getValue());
} else {
// assume the other operand will define the addition for me
// since add is commutative
return operand.plus(this);
}
}
然后换矩阵:
public Operand plus(Operand operand) {
if (Scalar.class.equals(operand.getClass())) {
// return a matrix where we add scalar value to all matrix elements
} else if (Matrix.class.equals(operand.getClass())) {
// return a matrix where we perform a scalar addition between each element
} else {
// assume the other operand will define the addition for me
// since add is commutative
return operand.plus(this);
}
}
这个想法是,无论什么时候我引入一个实现操作数类型(比如向量)的新类,我只需要在新操作数和所有其他现有操作数之间定义加上运算符 。即我不必重写标量和矩阵类的 的加号方法。
这种做法符合目标1和3,但不是2:所有操作返回 操作数的对象,并强迫我做了很多的铸造和 类在运行时,这似乎不是一个好的做法检查。
任何更好的方法来解决我的问题?
对于初学者,使用`instanceof`运算符而不是`getClass()` – OrangeDog 2010-12-22 18:01:27
谢谢。这就说得通了。 – double07 2010-12-23 01:43:11