コードが重複している状況があり (またはそうですか?)、それを回避する方法がわかりませんが、コードを明確に保ちます。
状況を非常に単純化しておきます。
// 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 メソッドと基本的に同じであることです。ここで言及した 2 つよりもはるかに多くの型があり、一部のメソッド add は同じではないことに注意してください。
これはコードの重複ですか? もしそうなら、それを避ける方法はありますか?1つも思い浮かばないので。
また、 add メソッドで、 if (instanceof ) ステートメントを使用せずに、オペランドが持つことができるさまざまな型を切り替えるにはどうすればよいですか?