This might be a very basic question with a very obvious answer but i am having hard time figuring this out.
How to know the return type of a method of a class involve in java factory patterns. for example looking at the code below... what would be the return type of the method invocation and how to cast it properly... and also how to write the javadoc also for the classes.
i am trying to write a library which user then can plug in to their project...
I have an interface
public interface myInterface
{
public Object doA();
public Object doB();
}
and concrete Classes as follow
public class concerete1 implements myInterface
{
public concerete1() {
}
@override
public Object doA()
{ return new String("Hello"); }
@override
public Object doB()
{ return "hello".getBytes(); }
}
and
public class concerete1 implements myInterface
{
public concerete2() {
}
@override
public Object doA()
{ return "hello".getBytes(); }
@override
public Object doB()
{ return new String("Hello"); }
}
and my factory class is as follow
public class factory
{
private myInterface mi;
public myInterface actionProducer(String choice)
{
switch(choice)
{
case "a":
mi = new concerete1();
break;
case "b":
mi = new concerete2();
break;
}
return mi;
}
}
and my test runner class is as follow
String result = factory.actionProducer("a").doA();
You should not have to explicitly test the dynamic type of a factory method's return value. The static type should tell you all you need to know. That means the return type should be as specific as it needs to be to tell you what you can do with the object. For example, a factory method that makes maps of varying implementation should return Map
:
public interface MapFactory {
public Map makeMap();
...
}
Whether the Map
is a HashMap
or TreeMap
or ConcurrentSkipListMap
, you can use the Map
methods to interact with it. If it turns out you need to call ceilingKey
, which isn't a Map
method, you have a design problem.
In your case, your factory methods make no sense, since there is no more specific type to return than Object
, and nothing you can do with the return values beyond the API of Object
. A more reasonable factory would return objects that can be interacted with the same way, regardless of how the objects are implemented.