how about having a Map of Condition to Class, and instantiate the class? so rather than having
public MyType getNewObject(String id) {
if ( id.equals("first") return new First();
if ( id.equals("second") return new Second();
...
}
you'd have something like (VERY oversimplified)
private Map<String, Class> map;
...
public MyType getNewObject(String id) {
Class clazz = map.get(id);
// there will be some exceptions to handle here IRL
return (MyType) clazz.newInstance();
}
the Map gets populated by a static initializer or in the constructor or wherever. Or, you could take this further still by adopting - as the other guy said - some more reflection, that way you could populate the Map from a config file, and have yourself the beginnings of a pluggable application
private Map<String, String> map;
...
public MyType getNewObject(String id) {
Class clazz = Class.forName(map.get(id));
return (MyType) clazz.newInstance();
}
just musing, something to chew on :)
import java.util.*;
interface Life
{
}
class Adam extends Dna implements Life
{
private static Map Helix = new HashMap();
public static Map GetHelix() {
return Adam.Helix;
}
static {
Adam.Helix.put( "father", "aaa" );
Adam.Helix.put( "mother", "bbb" );
};
protected Adam() {
}
}
class Eve extends Dna implements Life
{
private static Map Helix = new HashMap();
public static Map GetHelix() {
return Eve.Helix;
}
static {
Eve.Helix.put( "father", "ccc" );
Eve.Helix.put( "mother", "ddd" );
};
protected Eve() {
}
}
class Dna
{
public Dna( Map h ) {
this.m = h;
}
public Dna() {
}
private static Map Pool = new HashMap();
static {
Pool.put( Eve.GetHelix(), new Eve() );
Pool.put( Adam.GetHelix(), new Adam() );
};
public static Life Create( Dna s ) {
Iterator it = Dna.Pool.keySet().iterator();
while( it.hasNext() ) {
Map k = (Map) it.next();
if( Dna.Match( k, s ) ) {
return (Life) Dna.Pool.get( k );
}
}
return null;
}
private static boolean Match( Map c, Dna d ) {
Iterator it = d.GetHelix().keySet().iterator();
while( it.hasNext() ) {
Object k = it.next();
Object v = d.GetHelix().get( k );
if( ! c.containsKey( k )
|| ! c.containsValue( v ) ) {
return false;
}
}
return true;
}
private static Map m = new HashMap();
public static Map GetHelix() {
return m;
}
}
public class DoGyrotcaF
{
public static void main( String[] args ) {
Map m = new HashMap();
m.put( "father", "123" );
m.put( "mother", "abc" );
Dna dna = new Dna( m );
System.out.println( "c: " + Dna.Create( dna ) );
m.clear();
m.put( "father", "aaa" );
m.put( "mother", "bbb" );
dna = new Dna( m );
System.out.println( "c: " + Dna.Create( dna ) );
m.clear();
m.put( "father", "ccc" );
m.put( "mother", "ddd" );
dna = new Dna( m );
System.out.println( "c: " + Dna.Create( dna ) );
}
}