Java工廠中,對于產品的入庫和出庫是非常重要的環節。本文就針對這兩個環節分別進行說明:
1. 產品入庫
public class Product { private String name; private int quantity; public void setName(String name) { this.name = name; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getName() { return name; } public int getQuantity() { return quantity; } } public interface ProductFactory { Product createProduct(String name); void storeProduct(Product product); } public class ProductFactoryImpl implements ProductFactory { @Override public Product createProduct(String name) { Product product = new Product(); product.setName(name); product.setQuantity(0); return product; } @Override public void storeProduct(Product product) { // 存儲產品到數據庫或其他存儲設備中 } }
上述代碼展示了產品類和產品工廠類,其中產品類包含了產品的名稱(name)和數量(quantity)屬性,而產品工廠類除了創建產品(createProduct)外,還提供了將產品存儲(storeProduct)功能。在產品入庫時,只需調用工廠類的createProduct方法創建一個新的產品,再調用storeProduct方法進行存儲即可。
2. 產品出庫
public class Warehouse { private Mapproducts; public Warehouse() { products = new HashMap<>(); } public void addProduct(String name, int quantity) { if (products.containsKey(name)) { products.put(name, products.get(name) + quantity); } else { products.put(name, quantity); } } public boolean removeProduct(String name, int quantity) { if (!products.containsKey(name)) { return false; } int currentQuantity = products.get(name); if (quantity >currentQuantity) { return false; } products.put(name, currentQuantity - quantity); return true; } } public class ProductFactoryImpl implements ProductFactory { private Warehouse warehouse; public ProductFactoryImpl() { warehouse = new Warehouse(); } @Override public Product createProduct(String name) { Product product = new Product(); product.setName(name); product.setQuantity(0); warehouse.addProduct(name, 0); return product; } @Override public void storeProduct(Product product) { warehouse.addProduct(product.getName(), product.getQuantity()); } public boolean removeProduct(String name, int quantity) { return warehouse.removeProduct(name, quantity); } }
上述代碼展示了一個倉庫(Warehouse)類和針對產品出庫的修改后的產品工廠類。在倉庫類中,我們使用Map存儲了產品名稱(name)和數量(quantity)的對應關系。在進行產品出庫時,只需調用工廠類的removeProduct方法,指定對應的產品名稱和數量即可。如果對應產品不存在或庫存不足,則removeProduct方法返回false。
上一篇php amp 換成
下一篇415PHP