我有一个基于接口的现有设计,该接口公开了一个API方法,该方法当前返回void。有很多不同的实现类来实现这个接口。但是,现在我想做一个更改,以便这些实现中很少有应该返回一个对象。显而易见的解决方案似乎是:使所有的实现返回"对象",并期望返回的值在不需要的地方被忽略。但是对于这样的重构,是否有更清晰更好的解决方案呢?
是否有任何设计模式,可以在这里应用,这将使设计更好,以防我不得不改变所有现有的实现,是否需要。
说明如下:
//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
}
}
一种选择是创建一个新接口CommonInterface2,它实现新方法。这需要更改"这些实现中的少数几个",而不是"许多实现类"。
public interface CommonInterface2 extends CommonInterface {
public Object commonMethodAndReturn();
}
只在返回对象的实现子集中实现。
public class OneOfTheFew implements CommonInterface2 { ... }
public class OneOfTheMany implements CommonInterface { ... }
仅在需要返回值时测试新接口。
public void foo( CommonInterface ci ) {
if ( ci instanceof CommonInterface2 ) {
CommonInterface2 ci2 = (CommonInterface2) ci;
...
}
}