java - 代码重复(或不重复)- JAVA

标签 java interface instanceof code-duplication

我有代码重复的情况(或者是吗?),我不知道如何避免它,但我的代码仍然保持清晰。

让我把情况大大简化:

// 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/

相关文章:

java - 在Java中将位图图像转换为未压缩的tif图像

c# - Box C# 对象作为通用接口(interface)

java - 比较父类型的两个子类型时正确的 API 实现

java - 通过创建依赖于特定条件的对象来避免 If-else 代码异味

C++接口(interface)设计问题

android-studio - 为什么 AS 告诉我 `(ob instanceof Button)` 总是 `false` ?

java - Scala如何获取其JVM环境?

java - tomcat运行shell脚本并将进程返回给系统

java - 将特定用户保存的多个 url 插入数据库的最佳方法是什么?

java - 实现并通过方法向 ArrayList 添加项目