سؤال

I found this construct in some code.

Is there any benefit to have a private static class implement A? This reminded me of the Pimpl idiom in C++. Is there any benefit to using the Pimpl idiom in Java?

public abstract class A {
    public void doStuff();

    public static A getNewInstance() {
       return new AImpl();
    }

    private static class AImpl extends A {
        public void doStuff()  {
           ....
        }    
    } 

}
هل كانت مفيدة؟

المحلول

Is there any benefit to have a private static class implement A?

Well, it hides the implementation away completely, so from an encapsulation point of view it's quite nice. One situation I've seen this in a few times is custom comparators. For example:

public class Person
{
    public static final Comparator<Person> NAME_COMPARATOR = new NameComparator();
    public static final Comparator<Person> AGE_COMPARATOR = new AgeComparator();

    // Name, age etc properties

    private static class NameComparator implements Comparator<Person>
    {
        ...
    }

    private static class AgeComparator implements Comparator<Person>
    {
        ...
    }
}

There's no real need for the comparator implementation classes to be visible outside Person, and it's nice to be able to get an instance easily via the public static field.

No callers need to know the implementation - there could just be one comparator class which takes parameters, for example - they just express which comparator they want via the constants. (You could equally use an enum for this, of course.)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top