代码重复(或不重复)-JAVA
作者:互联网
我遇到了代码重复的情况(或者是?),我不知道如何避免它,但是仍然保持代码的清晰.
让我大大简化这种情况:
// 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)语句的情况下在各种类型的操作数之间切换?
解决方法:
您可以使用抽象类,并为其提供具体的add方法.
标签:interface,instanceof,code-duplication,java 来源: https://codeday.me/bug/20191101/1980058.html