目录
空白枚举+集合
public enum WeaponType {
SWEAR
}
public class WeaponFactory {
private static final HashMap<WeaponType, Weapon> hashMap = new HashMap<>() {
{
put(WeaponType.SWEAR, new Swear());
}
};
public static Weapon newInstance(WeaponType weaponType) {
return hashMap.get(WeaponType.SWEAR);
}
}
枚举+Supplier
@Getter
@RequiredArgsConstructor
public enum WeaponType {
SWEAR(Swear::new);
private final Supplier<Weapon> weaponConstructor;
}
public class WeaponFactory {
public static Weapon newInstance(WeaponType weaponType) {
return weaponType.getWeaponConstructor().get();
}
}
反射
public class WeaponFactory {
public static Weapon newInstance(Class<? extends Weapon> weaponClass, Object... args) {
Class<?>[] parameters = (Class<?>[]) Arrays.stream(args).map(Object::getClass).toArray();
try {
return weaponClass.getConstructor(parameters).newInstance();
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
反射+枚举
@Getter
@RequiredArgsConstructor
public enum WeaponType {
SWEAR(Swear.class);
private final Class<? extends Weapon> weaponClass;
}
public class WeaponFactory {
public static Weapon newInstance(WeaponType weaponType, Object... args) {
Class<? extends Weapon> weaponClass = weaponType.getWeaponClass();
Class<?>[] parameters = (Class<?>[]) Arrays.stream(args).map(Object::getClass).toArray();
try {
return weaponClass.getConstructor(parameters).newInstance();
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}