Загрузка данных


package model;

import java.util.HashMap;
import java.util.Map;

public class Inventory {
    private static Inventory instance;
    private Map<Integer, Product> products = new HashMap<>();

    private Inventory() {
        products.put(1, new Product("Чек (счёт)", 50, 5));
        products.put(2, new Product("Шоколадный батончик", 75, 3));
        products.put(3, new Product("Питьевая вода", 40, 4));
    }

    public static Inventory getInstance() {
        if (instance == null) instance = new Inventory();
        return instance;
    }

    public Product getProduct(int id) { return products.get(id); }

    public void showProducts() {
        System.out.println("\nДоступные товары:");
        for (var e : products.entrySet())
            System.out.println(e.getKey() + ". " + e.getValue().name + " - " + e.getValue().price + " руб. (остаток: " + e.getValue().quantity + ")");
    }

    public boolean buy(int id) {
        Product p = products.get(id);
        if (p != null && p.quantity > 0) {
            p.quantity--;
            return true;
        }
        return false;
    }

    // Новый метод для отмены покупки
    public void restoreProduct(int id) {
        Product p = products.get(id);
        if (p != null) {
            p.quantity++;
        }
    }
}