irishMTS irishMTS - 9 days ago 6
Java Question

How to allow a user to choose what class to initialise

I have an

abstract class Foo
, which contains a function
a(Object o)
.

Depending on what implementation of
Foo
you use,
a(Object o)
is implemented slightly differently.

I want the user of the program to be able to determine what implementation of
Foo
is used (eg.,
aFoo
,
bFoo
,
cFoo
, etc), but I want to cut down on my use of conditional logic so that I can add to my program more safely in the future.

I currently have an
Enum eBar
that holds the names of all the implementations of
Foo
, which the user can choose from, but I am unable to determine how to use that to initialise the class.

Answer

Store the instance of Foo to use, or add a method creating the Foo to use, in each enum instance:

public enum FooType {
    A {
        @Override
        public Foo createFoo() {
            return new AFoo();
        }
    },
    B {
        @Override
        public Foo createFoo() {
            return new BFoo();
        }
    }

    public abstract Foo createFoo();
}

Then, once the user has chosen the type, all you need to do is

selectedFooType.createFoo().a(object);
Comments