2
我有一個基於接口的現有設計,它暴露了一個API方法,它現在返回void。並且有很多不同的實現類實現了這個接口。但是,現在我想進行更改,以便這些實現中很少應該返回一個Object。明顯的解決方案似乎是:使所有實現返回「Object」,並期望返回的值在不需要的地方被忽略。但是,對於這種重新分解,是否有更清晰更好的解決方案?更改現有接口API方法以返回對象而不是無效的最佳方法?
是否有任何設計模式可以在這裏應用,這將使設計更好,以防萬一我必須對所有現有實現進行更改(無論是否需要)。下面
插圖:
//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
}
}
事實上,你從一些而不是其他人返回一個值,這些實現代表兩個不同的概念/操作。也許如果你瞭解這些類的作用,我們可以提出更好的建議。不斷檢查子接口和向下轉換會變得混亂,並且總是檢查空結果。 – jeff 2013-04-24 21:47:00
這些類用於處理從命令行收到的命令的處理。每個類都具有其處理的命令類型的特定邏輯。該接口提供了一個通用API,通過它可以在運行時處理任何類型的命令。突然間有一個用例,其中一些命令需要返回某些內容(而不僅僅是顯示結果),以便該返回值可用於其他目的。基本上,試圖重用現有的代碼。 – unni 2013-04-26 09:11:00