我有代码重复的情况(或者是吗?),我不知道如何避免它,但我的代码仍然保持清晰。
让我把情况大大简化:
// let's say I have a interface Entity
interface Entity {
public Entity add (Entity operand);
}
// And two classes that implement this interface
class MyInteger implements Entity {
private int value;
public Entity add (Entity operand)
{
// here I have to manage the situation distinctly if operand is a MyInteger or MyString
}
}
class MyString implements Entity {
private String value;
public Entity add (Entity operand )
{
}
}
现在,我的问题是 MyString 中的 add 方法与 MyInteger 中的 add 方法基本相同。请记住,我有比这里提到的两种更多的类型,并且对于某些方法 add 是不一样的。
这段代码重复了吗?如果是这样,有没有办法避免它?因为我似乎想不出一个。
此外,在 add 方法中,如何在不使用 if (instanceof) 语句的情况下在各种类型的操作数之间切换?
最佳答案
您可以使用抽象类并为其提供具体的添加方法。
关于java - 代码重复(或不重复)- JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11966510/