2

現在 void を返す 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
   }
}
4

1 に答える 1

2

1 つのオプションは、新しいメソッドを実装する新しいインターフェイス 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;
        ...
    }
 }
于 2013-04-22T18:23:57.420 に答える