I’m a new Java/OO programmer. I would like to create a method (referred to below as myMethod) which returns one of n types of objects based on inspecting input parameters and the state of the world. Say here n == 2 for simplicity: myMethod() can return an object of either type Foo or Bar.
Foo and Bar have different methods available to call on them, some exclusive and some in common, such as:
ReturnType? myMethod(inputs) {
if (/*examining state of world & inputs implies a Foo*/)
return new Foo();
return new Bar();
}
...
public class Foo {
public Foo() {}
public void x() {...} //common to Bar
public void f() {...}
}
public class Bar {
public Bar() {}
public void x() {...} //common to Foo
public void b() {...}
}
What design pattern should I use for myMethod(), and for the classes Foo and Bar? If my method’s return type is a superclass (or an aggregation?) of Foo and Bar or if Foo & Bar implement some common interface, then is there a way for clients who receive objects from myMethod() to be able to safely call f() or b() on the returned object without needing to use object introspection or casting?
Or is this design an anti-pattern, and is there an obvious rewrite I’m missing? Thanks.
No pattern – you can’t do it with knowing the type and casting.
You either have to pull those methods up to the common interface or parent class OR cast. There’s no “pattern” to save you – that’s magical thinking.