Design pattern to "toString" a third party object
I have a third party object which uses the toString method inherited from Java.lang.Object. This method is pretty useless. However I can't think of a clean design to override this behavior. Different approaches below.
- Subclass and override the toString method.
The problem: if any calls int开发者_Go百科ernal to the original object call toString and inspect the returned String, they will now break. I don't want to break the existing object, or assume anything about the cleanliness of the third-party code.
- Create a StringFactory with a createString method.This method calls toString on all objects other than my third-party object in question, but for my object builds a String in my custom way.
The problem: I can neither require that everything gets passed to the createString method and never called toString on directly (this would be ludicrous across a large code base) nor can I easily remember which objects should be passed, because there is custom logic for them.
Does anyone have a design pattern that feels clean?
Just use a static method on a util class:
public class MyUtils {
public static String toString(My3rdPartyClass obj) {
// impl here
}
}
I really like Bohemian's answer.
With that in mind, an OOP way to solve it would be
class My3rdPartyClassFormatter {
private My3rdPartyClass data;
public My3rdPartyClassFormatter(My3rdPartyClass d) { this.data = d; }
public String toString() {
// impl here
}
}
Use a proxy. Your invocation handler will intercept all calls to the 3rd party object. In most cases, it will just pass them through. However, implement your own toString logic.
InvocationHandler handler = new InvocationHandler
{
private ThirdParty thrd ;
public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable
{
if ( method . getName().equals ( "toString" ) )
{
return "useful string" ;
}
else
{
return method . invoke ( thrd , args ) ;
}
}
}
精彩评论