我有一个艰难的我试图包围我的头。我有一些公共接口和一些包私人类,如下所示。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);
}
}
}
}
我不太了解你不喜欢上面的代码。它对我来说很好。 – gpeche 2010-09-16 21:12:30
尝试显示如何从外部类中调用此功能,以及从该角度不必要地暴露什么“内部细节”。 – 2010-09-16 22:33:58