我有一個代碼重複的情況(或是否?),我不知道如何避免它,但仍然保持清晰的代碼。代碼重複(或不) - 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