java 不重复码_代码重复(或不重复)-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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值