Ensuring interoperability between members with low-level generics

Let's say I create a general AssemblyLineclass that takes physical objects, measures them, puts them in cardboard boxes, and suppresses them. I want users to be able to provide their own strategies for measuring objects (maybe some care about the total volume, and some just care about the longest measurement of an object), as well as their own strategies for selecting boxes (since users will know better which cardboard they want to use).

It would be great if I AssemblyLinecould adopt measurement strategies and field selection strategies that work on superclasses of a physical object. After all, if the user has a measurement strategy that works for all types Dessert, we must allow them to use the same strategy in their own AssemblyLine<Cake>as well as in AssemblyLine<Pie>, right?

So, start with a measurement strategy:

public interface PhysicalObjectMeasurementStrategy<T> {
    Measurement measureObject(T object);
}

Simple enough, and I find it undeniable. Then we want to define an interface for the field selection strategy. This may be my first mistake, but let the roll with her for now:

public interface CardboardBoxSelectionStrategy<T> {
    CardboardBoxSize chooseCardboardSizeForObject(T object, PhysicalObjectMeasurementStrategy<? super T> measurementStrategy);
}

, , . , , .

, :

public class AssemblyLine<T> {
    private final PhysicalObjectMeasurementStrategy<? super T> measurementStrategy;
    private final CardboardBoxSelectionStrategy<? super T> boxSelectionStrategy;

    // ...
    public void giftWrapObject(final T physicalObject) {
        // Here where things fall apart:
        boxSelectionStrategy.chooseCardboardSizeForObject(physicalObject, this.measurementStrategy);

        // ...
    }
}

, ( !), , , measurementStrategy boxSelectionStrategy T, ( ). , , :

  • PhysicalObjectMeasurementStrategy<Cylindrical>
  • CardboardBoxSelectionStrategy<Edible>
  • AssemblyLine<Cake>

, Cylindrical Edible ( ), .

, : , , , AssemblyLine? , ( ?), , , ?

, !

+4
1

- :

class AssemblyLine<M, B extends M> {
    private final PhysicalObjectMeasurementStrategy<M> measurementStrategy;
    private final CardboardBoxSelectionStrategy<B> boxSelectionStrategy;

    public void giftWrapObject(B physicalObject) {...

, , , :

<R extends T> CardboardBoxSize chooseCardboardSizeForObject(R object, 
        PhysicalObjectMeasurementStrategy<? super R> measurementStrategy);

, .

, .

0

All Articles