mercredi 21 novembre 2018

Applying Factory Pattern Extensively

I'm developing a game and there are tons of occasions where I need some sort of factory pattern involved. In an attempt not to create lots of Factory class methods, I used Supplier<T> instead. This works great but not if there are required arguments.

It works in this case: () -> new Spawn(3, 6, "example");

But sometimes I need to pass other parameters to the factory. There's the Consumer and BiConsumer which accept two parameters. But there's no interface for 3, 4, 5...

I came up with an embarassing solution to this problem, but it illustrates what I'm trying to achieve. What other solutions are there?

import java.util.function.Function;

public class FactoryExample {

    static class Args {
        Object[] objs;
        Args(Object ...objs) { this.objs = objs; }
        Object[] get() { return objs; }
    }

    static class Thing {
        int a; char b; boolean c;
        Thing(int a, char b, boolean c) {
            this.a = a; this.b = b; this.c = c; }
    }

    static class Number {
        int x;
        Number(int x) { this.x = x; }
    }


    public static void main(String[] args) {

        Function<Args, Number> factoryA = arg -> {
            int x = (int) arg.get()[0];
            return new Number(x);   
        };

        Function<Args, Thing> factoryB = arg -> {
            int a = (int) arg.get()[0];
            char b = (char) arg.get()[1];
            boolean c = (boolean) arg.get()[2];
            return new Thing(a, b, c);
        };

        factoryB.apply(new Args(3, 'a', true));
        factoryA.apply(new Args(3));
    }

}

Aucun commentaire:

Enregistrer un commentaire