Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic factory method convention

Tags:

java

generics

Let me say there is an abstract class which looks like

abstract class Parent<V> {

    protected static <T extends Parent<V>, V> T newInstance(
        final Class<T> type, final V value) {
        // ...
    }
}

Within following Child class

class Child extends Parent<XXX> {

    public static Child newInstance1(final XXX value) {
        // ...
    }

    public static Parent<XXX> newInstance2(final XXX value) {
        // ...
    }
}

Which one is preferable? newInstance1 or newInstancw2?

like image 274
Jin Kwon Avatar asked Mar 12 '13 05:03

Jin Kwon


2 Answers

It actually depends on the scenario in which you are you using the newInstance(). In most general cases:

Since Child is implementing newInstance(), According to me

protected static Child newInstance() 
{
    // ...
}

would be more appropriate.

like image 139
codeMan Avatar answered Oct 02 '22 16:10

codeMan


Usually, factory method defined inside some class returns instance of this particular class, so it should be:

public class Foo ...
{
    public static Foo newInstance ()
    {
        ...
    }
}

regardless of what class this class extends and what interfaces it implements.

like image 26
Mikhail Vladimirov Avatar answered Oct 02 '22 14:10

Mikhail Vladimirov