简体   繁体   中英

What design pattern could work with such a generic type in Java?

Consider having a generic type:

public interface <T> Assigner {
    <S> S assign(T type);
}

Now, let's say I want to have different types of assigners that could assign an object of any type T to a group of any type S . Example:

interface PlayerAssigner extends Assigner<Player> {
    <S> S assign(Player player);
}

interface ManagerAssigner extends Assigner<Manager> {
    <S> S assign(Manager manager);
}

...

I would also like to introduce a group-type-based assigner, but this is where I got stuck. I tried:

interface CityBasedAssigner<T> extends Assigner<T> {
    City assign(T type);
}

, but this won't work, it says that both methods have the same erasure. I don't know whether it should be an abstract class or something different, or whether the whole concept could be simplified. What I want is to be able to instantiate different types of assigners from the combination of two type parameters, eg CityBasedPlayerAssigner, CountryBasedPlayerAssigner, CountryBasedManagerAssigner, etc., and this would have been the next step: combining the two extended interfaces and create many implementations based on these two.

What am I missing here?

Your sub interface inherits the method assign from Assigner . All you need to do in the sub interface is pass the types to the super interface.

interface Assigner<S, T> { S assign(T type);}
interface PlayerAssigner<S> extends Assigner<S,Player> {}
interface ManagerAssigner<S> extends Assigner<S,Manager> {}
interface CityBasedAssigner<T> extends Assigner<City,T> {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM