gpt4 book ai didi

java - 避免类上的代码重复

转载 作者:行者123 更新时间:2023-12-02 02:54:39 24 4
gpt4 key购买 nike

我正在编写一些类,它们都实现了从接口(interface)继承的特定方法。除了对某个其他函数的一次调用之外,此方法对于所有类都接近相同。

例如:

public void doSomething(){
int a = 6;
int b = 7;
int c = anOtherMethod(a,b);
while(c < 50){
c++;
}
}

如果多个类都有函数 doSomething() 但方法 anOtherMethod() 的实现不同怎么办?

在这种情况下如何避免代码重复? (这不是我的实际代码,而是一个简化版本,可以帮助我更好地描述我的意思。)

最佳答案

这看起来像是 template method pattern 的一个很好的例子。 .

  1. doSomething 放入基类中。
  2. 也在该基类中声明abstract protected anotherMethod,但不提供实现。
  3. 每个子类都会为 anotherMethod 提供正确的实现。

关于java - 避免类上的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51813558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com