| 1 | package BehaviouralDesignPatterns.StateDesignPattern; |
| 2 | |
| 3 | public class Inventory { |
| 4 | |
| 5 | ItemShelf[] itemShelves = null; |
| 6 | |
| 7 | Inventory(int itemCount) { |
| 8 | itemShelves = new ItemShelf[itemCount]; |
| 9 | initialEmptyInventory(); |
| 10 | } |
| 11 | |
| 12 | public ItemShelf[] getItemShelves() { |
| 13 | return itemShelves; |
| 14 | } |
| 15 | |
| 16 | public void setItemShelves(ItemShelf[] itemShelves) { |
| 17 | this.itemShelves = itemShelves; |
| 18 | } |
| 19 | |
| 20 | public void initialEmptyInventory() { |
| 21 | int startCode = 101; |
| 22 | for (int i = 0; i < itemShelves.length; i++) { |
| 23 | ItemShelf space = new ItemShelf(); |
| 24 | space.setCode(startCode); |
| 25 | space.setSoldOut(true); |
| 26 | itemShelves[i]= space; |
| 27 | startCode++; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | public void addItem(Item item, int codeNumber) throws Exception { |
| 32 | |
| 33 | for (ItemShelf itemShelf : itemShelves) { |
| 34 | if (itemShelf.code == codeNumber) { |
| 35 | if (itemShelf.isSoldOut()) { |
| 36 | itemShelf.item = item; |
| 37 | itemShelf.setSoldOut(false); |
| 38 | } else { |
| 39 | throw new Exception("already item is present, you can not add item here"); |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | public Item getItem(int codeNumber) throws Exception { |
| 46 | |
| 47 | for (ItemShelf itemShelf : itemShelves) { |
| 48 | if (itemShelf.code == codeNumber) { |
| 49 | if (itemShelf.isSoldOut()) { |
| 50 | throw new Exception("item already sold out"); |
| 51 | } else { |
| 52 | |
| 53 | return itemShelf.item; |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | throw new Exception("Invalid Code"); |
| 58 | } |
| 59 | |
| 60 | public void updateSoldOutItem(int codeNumber){ |
nothing calls this directly
no outgoing calls
no test coverage detected