-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path33.DesignAnInventoryManagementSystem.java
More file actions
124 lines (103 loc) · 2.88 KB
/
33.DesignAnInventoryManagementSystem.java
File metadata and controls
124 lines (103 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
class Item {
private int id;
private String name;
private int quantity;
private double price;
public Item(int id, String name, int quantity, double price) {
this.id = id;
this.name = name;
this.quantity = quantity;
this.price = price;
}
public void setQuantity(int q) {
this.quantity = q;
}
public int getId() {
return this.id;
}
@Override
public String toString() {
return "[ID=" + id + "] " + name + " | Qty=" + quantity + " | Price=" + price;
}
}
// -------------------------
// Inventory Singleton
// -------------------------
class Inventory {
private static Inventory instance = null;
private final HashMap<Integer, Item> items;
private int idCounter;
private final ReentrantLock lock;
private Inventory() {
items = new HashMap<>();
idCounter = 1;
lock = new ReentrantLock();
}
public static Inventory getInstance() {
if (instance == null) {
synchronized (Inventory.class) {
if (instance == null) {
instance = new Inventory();
}
}
}
return instance;
}
public int addItem(String name, int qty, double price) {
lock.lock();
try {
int newId = idCounter++;
items.put(newId, new Item(newId, name, qty, price));
return newId;
} finally {
lock.unlock();
}
}
public boolean updateQuantity(int itemId, int qty) {
lock.lock();
try {
Item it = items.get(itemId);
if (it != null) {
it.setQuantity(qty);
return true;
}
return false;
} finally {
lock.unlock();
}
}
public Item getItem(int itemId) {
return items.get(itemId);
}
public Item deleteItem(int itemId) {
lock.lock();
try {
return items.remove(itemId);
} finally {
lock.unlock();
}
}
public List<Item> listItems() {
return new ArrayList<>(items.values());
}
}
// -------------------------
// DEMO EXECUTION
// -------------------------
public class InventorySystem {
public static void main(String[] args) {
Inventory inv = Inventory.getInstance();
int id1 = inv.addItem("Apple", 50, 2.5);
int id2 = inv.addItem("Banana", 100, 1.2);
System.out.println("Initial Items:");
System.out.println(inv.listItems());
inv.updateQuantity(id1, 70);
System.out.println("\nAfter Updating Apple Qty:");
System.out.println(inv.getItem(id1));
inv.deleteItem(id2);
System.out.println("\nAfter Removing Banana:");
System.out.println(inv.listItems());
}
}