Java – third party object whose design pattern is “toString”

I have a third-party object that uses from Java ToString method inherited from lang.Object This method is useless But I can't think of a clean design to cover this behavior The following are different methods

>Subclass and override the toString method

Problem: if any calls inside the original object call toString and check the returned string, they will now break I don't want to break existing objects or assume the cleanliness of third-party code

>Use the createstring method to create a stringfactory This method calls toString on all objects except the third-party objects I discussed, but for my objects, I build a string in a custom way

Problem: I can neither require everything to be passed to the createstring method, nor call toString directly (which would be ridiculous in a large code base), nor can I easily remember which objects should be passed because they have custom logic

Does anyone have a design pattern that feels clean?

Solution

Just use static methods on the util class:

public class MyUtils {

    public static String toString(My3rdPartyClass obj) {
        // impl here
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>