我有一个代码重复的情况(或是否?),我不知道如何避免它,但仍然保持清晰的代码。代码重复(或不) - 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中添加是bassicly一样的方法加入MyInteger。请记住,我有比这里提到的两种类型更多的类型,并且对于某些方法add来说是不一样的。
此代码是否重复?如果是这样,有没有办法避免它?因为我似乎无法想到一个。
另外,在add方法中,如何在不使用if(instanceof)语句的情况下在各种类型操作数之间切换?
您是否听说过仿制药? – SiB 2012-08-15 08:59:20