Search code examples
javafactory-pattern

Java 1.4 Factory Question


I have a factory, and I want to restrict the possible values that may be passed into the get method.

public static class FooFactory{

 public static final String TYPE1= "type1";
 public static Foo getFoo(String type){
   switch(type){
    case "type1":
      return new Type1();
    }
   }

 }

To use this:

FooFactory.getFoo(FooFactory.TYPE1);

I'd like to restrict the parameters that may be passed in. Is an idea to make a Type abstract class, then subclass and use Type as the parameter?


Solution

  • Don't subclass it, just create a Type class with a private constructor that takes a stirng parameter, and define public Type constants.

    Something like this.

    public final class Type {
    
        public static final Type FOO = new Type( "foo" );
        public static final Type BAR = new Type( "bar" );
    
        private String type;
    
        private Type( String type ) {
          this.type = type;
        }
    
        public String getType() { return type; }
    }