2010-09-16 63 views
1

我有一個艱難的我試圖包圍我的頭。我有一些公共接口和一些包私人類,如下所示。java類/接口適配器問題

基本上我的包私有類(以下稱爲UltraDecoder)需要一些蹩腳的解碼邏輯來解碼數據並對其執行一些操作以供其內部使用。不過,我也想利用這種蹩腳的解碼邏輯用於其他目的。我似乎無法做的是找出一個好方法,將我的蹩腳解碼邏輯作爲外部類可以使用的接口導出,也可以在內部使用我的UltraDecoder類,而不會暴露UltraDecoder的內部細節。

有什麼建議嗎?

/** structured metadata */ 
public interface Metadata { ... } 

/** 
* an opaque data item that can be unpackaged 
* to zero or more pairs of (Metadata metadata, int value) 
*/ 
public interface DataItem { ... } 

public interface SuperDecoder { 
    ... 
    /** decodes the item and passes each (metadata, value) pair 
    * to a listener by calling its onUpdate() method 
    */ 
    public void decode(DataItem item, SuperDecoderListener listener); 
} 

public interface SuperDecoderListener { 
    public void onUpdate(Metadata m, int value); 
} 

/* package-private classes implementation classes follow */ 
class UltraDecoder implements SuperDecoder 
{ 
    static private class SmartObjectWithMetadata 
    { 
     final private Metadata metadata; 
     public Metadata getMetadata(); 
    } 

    private interface UltraDecoderListener 
    { 
     public void onUpdate(SmartObjectWithMetadata, int value); 
    } 

    private void ultraDecode(DataItem item, UltraDecoderListener listener) 
    { 
     /* ... does lots of grungework to obtain 
     the (SmartObjectWithMetadata, value) pairs that correspond to this 
     DataItem. 

     Calls listener.onUpdate(smartObject, value) zero or more times. 
     */   
    } 

    public doSomething() 
    { 
     /* ... calls ultraDecode() ... this happens normally */ 
    } 
    @Override public void decode(DataItem item, 
     final SuperDecoderListener listener) 
    { 
     /* ??? how do we leverage ultraDecode ??? 
     * Below, we can do it but we have to create 
     * a new adapter object each time. 
     */ 
     ultraDecode(item, new UltraDecoderListener() { 
     @Override public void onUpdate(
      SmartObjectWithMetadata smartObject, 
      int value) 
     { 
      listener.onUpdate(smartObject.getMetadata(), value); 
     } 
     } 
    } 
} 
+0

我不太瞭解你不喜歡上面的代碼。它對我來說很好。 – gpeche 2010-09-16 21:12:30

+0

嘗試顯示如何從外部類中調用此功能,以及從該角度不必要地暴露什麼「內部細節」。 – 2010-09-16 22:33:58

回答

1

在與UltraDecoder相同的包中創建一個公共類DecoderUtil。

 
    public class DecoderUtil { 
     public static void decode(SuperDecoder decoder) { 
      //do common stuff 
      if(decoder instanceof UltraDecoder){ 
       //do stuff specific to UltraDecoder 
      } 
     } 
    } 
+0

我不明白這是如何工作的。接口是不同的。 – 2010-09-17 13:08:35

0

我有我自己的理解你的功能需求很難,但至少聽起來,你只需要一個public abstract class與已經實施的一些「默認」的邏輯,然後您可以在子類中重用。它被稱爲Template Method Pattern。在Java Collections和IO API中,您幾乎可以看到這一點。

0

您可以在UDL中爲onUpdate添加一個重載,該重載需要一個SDL參數?這就是說,我真的不會擔心物體創建的開銷,除非你知道這是一個問題。