HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Factory-like pattern implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
factorypatternimplementationlike

Problem

I have a hierarchy of types in my program and need to be able to create them dynamically at runtime. The solution I've come up with below is not the most elegant solution. Are there ways of improving it?

Specifically would it be possible to have the method getBuilderFor(...) not need to instantiate the type it's trying to create in order to get a builder for that type?

public class Main {

    public interface E {    }

    public class EImpl implements E { }

    public interface C extends E {

        interface Builder { T build(); }
    }

    public abstract class CImpl extends EImpl implements C {

        public abstract class BuilderImpl> implements Builder{  }
    }

    public interface B extends C { }

    public class BImpl extends CImpl implements B {

        public class BuilderImpl extends CImpl.BuilderImpl {
            @Override public B build() { return new BImpl(); }
        }
    }

    public interface D extends C { }

    public class DImpl extends CImpl implements D {

        public class BuilderImpl extends CImpl.BuilderImpl {
            @Override public D build() { return new DImpl(); }
        }
    }

    public class Factory {

        public , K extends C.Builder> K getBuilderFor(final Class type) {

            if (BImpl.class.equals(type)) {
                // I would ideally like to just have return BImpl.BuilderImpl() here - is it possible?
                return (K) new BImpl().new BuilderImpl();
            } else if (DImpl.class.equals(type)) {
                // I would ideally like to just have return DImpl.BuilderImpl() here - is it possible?
                return (K) new DImpl().new BuilderImpl();
            }
            return null;
        }
    }
}

Solution

Why not use a map of types (CImpl concrete instances) that are instantiated upon Factory initialization? The values of the map would be instances of BImpl, DImpl, etc, and the respective keys would be the types. The function getBuilderFor() would just do a map lookup and on the value returned from the map, call BuilderImpl() and return the result.

This approach would allow to avoid the if/else block. Additionally, it would make it easier and more elegant to add more types in the future.

Context

StackExchange Code Review Q#11903, answer score: 3

Revisions (0)

No revisions yet.