lundi 18 novembre 2019

Builder with generics

I have the following hierarchy

A doubly generic class named

public class Service<T, U> 
{
    private final Supplier<T>
    private final Function<T, U>
    private final Consumer<U>
    // more fields and methods ...
}

A Builder for that class ServiceBuilder<T, U> with the usual fluent API for builder

public class ServiceBuilder<T, U>
{
    private Supplier<T> supplier;
    private Function<T, U> mapper;
    private Consumer<U> consumer;
    // more fields and methods ....

    public ServiceBuilder<T, U> withSupplier(Supplier<T> supplier)
    {
        this.supplier = supplier;
        return this;
    }

    // more fields and methods ....

    public Service<T, U> build()
    {
        return new Service(supplier, mapper, consumer);
    }
}

Based on this, I want to provide a easy to use Supplier of T, lets say DummySupplier

public class NewObjectSupplier implements Supplier<SomeObject>
{
    public SomeObject get()
    {
        return new SomeObject();
    }
}

And I want a ServiceBuilder<SomeObject, T> that makes use of this supplier, effectively fixing T so that I only need a Function<SomeObject, U> mapper and a Consumer<U> consumer> to build my service.

How may I approach this? Extending ServiceBuilder does not work because all its existing methods that I want to reuse return ServiceBuilder and not some class extending ServiceBuilder ...

Is there some known pattern to approach?

Aucun commentaire:

Enregistrer un commentaire