Add item handler factory

This commit is contained in:
Richard Xu 2022-12-22 16:58:29 -05:00
parent cb1aa70657
commit 0dca9b86e1
2 changed files with 42 additions and 34 deletions

View File

@ -1,49 +1,20 @@
package com.gildedrose;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
class GildedRose {
private static final Map<ItemType, Class<? extends ItemHandler>> ITEM_HANDLER_MAP = Map.of(
ItemType.AGED_BRIE,
AgedBrieItemHandler.class,
ItemType.SULFURAS,
SulfurasItemHandler.class,
ItemType.BACKSTAGE_PASSES,
BackstagePassesItemHandler.class,
ItemType.CONJURED,
ConjuredItemHandler.class,
ItemType.GENERIC,
GenericItemHandler.class
);
// make package-private
public final List<Item> items;
final List<Item> items;
public GildedRose(Item[] items) {
this.items = Arrays.asList(items);
}
// todo: refactor this to use Guice
private static void handleDay(Item item) {
try {
ItemHandler itemHandler = ITEM_HANDLER_MAP
.get(ItemType.forDisplayName(item.name))
.getDeclaredConstructor()
.newInstance();
itemHandler.handleDay(item);
} catch (
InstantiationException
| IllegalAccessException
| InvocationTargetException
| NoSuchMethodException e
) {
throw new RuntimeException(e);
}
public void updateQuality() {
items.forEach(this::handleDay);
}
public void updateQuality() {
items.forEach(GildedRose::handleDay);
private void handleDay(Item item) {
ItemHandlerFactory.getItemHandler(item).handleDay(item);
}
}

View File

@ -0,0 +1,37 @@
package com.gildedrose;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
public class ItemHandlerFactory {
private static final Map<ItemType, Class<? extends ItemHandler>> ITEM_HANDLER_MAP = Map.of(
ItemType.AGED_BRIE,
AgedBrieItemHandler.class,
ItemType.SULFURAS,
SulfurasItemHandler.class,
ItemType.BACKSTAGE_PASSES,
BackstagePassesItemHandler.class,
ItemType.CONJURED,
ConjuredItemHandler.class,
ItemType.GENERIC,
GenericItemHandler.class
);
// todo: use guice
public static ItemHandler getItemHandler(Item item) {
try {
return ITEM_HANDLER_MAP
.get(ItemType.forDisplayName(item.name))
.getDeclaredConstructor()
.newInstance();
} catch (
InstantiationException
| IllegalAccessException
| InvocationTargetException
| NoSuchMethodException e
) {
throw new RuntimeException(e);
}
}
}