| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package cz.davza.studentadventure.objects;
- import cz.davza.studentadventure.base.ItemCollectionBase;
- import cz.davza.studentadventure.enums.CommandState;
- import cz.davza.studentadventure.interfaces.IItem;
- import cz.davza.studentadventure.interfaces.IObservable;
- import cz.davza.studentadventure.interfaces.IObserver;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Map;
- import java.util.Set;
- /**
- * The player's personal item inventory, with Observer support for change notifications.
- *
- * <p>Extends {@link ItemCollectionBase} with the full slot-based stacking logic,
- * and additionally implements {@link IObservable} so that external listeners
- * (such as a GUI panel) can react whenever the inventory contents change.</p>
- *
- * <p>Every call to {@link #Add} or {@link #Remove} automatically fires a
- * {@link CommandState#INVENTORY_CHANGE} notification to all registered observers
- * after delegating the operation to the superclass.</p>
- *
- * @see cz.davza.studentadventure.base.ItemCollectionBase
- * @see IObservable
- * @see IObserver
- */
- public class PlayerInventory extends ItemCollectionBase<IItem> implements IObservable {
- private final Map<CommandState, Set<IObserver>> observers = new HashMap<>();
- /**
- * Creates a new inventory with the given number of bulk-unit capacity.
- *
- * @param size the total bulk capacity of this inventory
- */
- public PlayerInventory(int size) {
- super(size);
- }
- /**
- * {@inheritDoc}
- *
- * <p>After the item is added (or partially added) by the superclass,
- * all observers registered for {@link CommandState#INVENTORY_CHANGE} are notified.</p>
- */
- @Override
- public int Add(IItem item, int count){
- int result = super.Add(item, count);
- notifyObservers(CommandState.INVENTORY_CHANGE);
- return result;
- }
- /**
- * {@inheritDoc}
- *
- * <p>After the item is removed by the superclass,
- * all observers registered for {@link CommandState#INVENTORY_CHANGE} are notified.</p>
- */
- @Override
- public void Remove(String itemCode, int count) {
- super.Remove(itemCode, count);
- notifyObservers(CommandState.INVENTORY_CHANGE);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public void addObserver(CommandState observedstate, IObserver o) {
- if (!observers.containsKey(observedstate)) observers.put(observedstate, new HashSet<>());
- observers.get(observedstate).add(o);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public void notifyObservers(CommandState notifiedState) {
- if (!observers.containsKey(notifiedState)) return;
- for (IObserver observer : observers.get(notifiedState)) {
- observer.update();
- }
- }
- }
|