gpt4 book ai didi

java - 更改现有接口(interface) api 方法以返回对象而不是 void 的最佳方法?

转载 作者:行者123 更新时间:2023-11-30 09:23:16 25 4
gpt4 key购买 nike

我有一个基于接口(interface)的现有设计,该接口(interface)公开了一个 API 方法,该方法当前返回 void。并且有许多不同的实现类实现了这个接口(interface)。但是,现在我想进行更改,以便这些实现中的少数应该返回一个对象。显而易见的解决方案似乎是:使所有实现都返回“对象”,并期望在不需要的地方忽略返回值。但是对于这样的重构有没有更干净更好的解决方案呢?

如果我必须对所有现有实现进行更改(无论是否需要),是否可以在此处应用任何设计模式来使设计变得更好。

下图:

//the interface
public interface CommonInterface{
public void commonMethod(); //this is where I want to change the return type
//to 'Object' for some of the implementations
}

//the factory
public CommonInterface getImplInstance() {

CommonInterface implInstance = instance; //logic to return corresponding instance
return implInstance;
}

//the implementation (there are multiple implemenations like this)
public class Impl1 implements CommonInterface {
public void commonMethod() {
//some logic
}
}

最佳答案

一个选项是创建一个新接口(interface) CommonInterface2,它实现了新方法。这需要更改“这些实现中的少数”而不是“许多实现类”。

  public interface CommonInterface2 extends CommonInterface {
public Object commonMethodAndReturn();
}

仅在返回对象的实现子集中实现它。

 public class OneOfTheFew implements CommonInterface2 { ... }
public class OneOfTheMany implements CommonInterface { ... }

仅在需要返回值的地方测试新接口(interface)。

 public void foo( CommonInterface ci ) {
if ( ci instanceof CommonInterface2 ) {
CommonInterface2 ci2 = (CommonInterface2) ci;
...
}
}

关于java - 更改现有接口(interface) api 方法以返回对象而不是 void 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16154013/

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