13. Proyecto Integrador: Carrito de Compras CRUD en Memoria
1. Arquitectura del Proyecto en Memoria RAM
En este proyecto integrador aplicaremos POO, Encapsulamiento, Composición, Arreglos/ArrayLists y operaciones CRUD (Create, Read, Update, Delete) para simular el comportamiento de una tienda en línea guardando todo en la memoria RAM del sistema.
- 📦 Categoria: ID y nombre de la categoría del producto (ej: "Electrónica", "Alimentos").
- 🛒 Producto: ID, nombre, precio, stock y su
Categoriaasociada. - 📋 ItemCarrito: Representa un producto añadido al carrito y su cantidad seleccionada (calculando subtotal).
- 🛍️ CarritoCompra: Maneja una lista dinámica de ítems con operaciones CRUD (Agregar, Listar, Modificar cantidad, Eliminar ítem, Vaciar).
- 🏬 TiendaManager: Almacena múltiples carritos independientes (ej: Carrito del cliente A vs Carrito del cliente B).
2. Clases Categoria y Producto
Categoria.java y Producto.java
JAVA
1// 1. Clase Categoria
2public class Categoria {
3 private int id;
4 private String nombre;
5
6 public Categoria(int id, String nombre) {
7 this.id = id;
8 this.nombre = nombre;
9 }
10
11 public int getId() { return id; }
12 public String getNombre() { return nombre; }
13
14 @Override
15 public String toString() {
16 return "[" + nombre + "]";
17 }
18}
19
20// 2. Clase Producto (Tiene una Categoria)
21public class Producto {
22 private int id;
23 private String nombre;
24 private double precio;
25 private int stock;
26 private Categoria categoria;
27
28 public Producto(int id, String nombre, double precio, int stock, Categoria categoria) {
29 this.id = id;
30 this.nombre = nombre;
31 this.precio = precio;
32 this.stock = stock;
33 this.categoria = categoria;
34 }
35
36 public int getId() { return id; }
37 public String getNombre() { return nombre; }
38 public double getPrecio() { return precio; }
39 public int getStock() { return stock; }
40 public void setStock(int stock) { this.stock = stock; }
41 public Categoria getCategoria() { return categoria; }
42
43 @Override
44 public String toString() {
45 return "#" + id + " " + nombre + " (" + categoria + ") - $" + precio + " [Stock: " + stock + "]";
46 }
47}
3. Clase ItemCarrito y CarritoCompra (Operaciones CRUD)
ItemCarrito.java y CarritoCompra.java (CRUD)
JAVA
1import java.util.ArrayList;
2
3// 3. Item en el Carrito
4public class ItemCarrito {
5 private Producto producto;
6 private int cantidad;
7
8 public ItemCarrito(Producto producto, int cantidad) {
9 this.producto = producto;
10 this.cantidad = cantidad;
11 }
12
13 public Producto getProducto() { return producto; }
14 public int getCantidad() { return cantidad; }
15 public void setCantidad(int cantidad) { this.cantidad = cantidad; }
16
17 public double getSubtotal() {
18 return producto.getPrecio() * cantidad;
19 }
20
21 @Override
22 public String toString() {
23 return producto.getNombre() + " x" + cantidad + " | Subtotal: $" + String.format("%.2f", getSubtotal());
24 }
25}
26
27// 4. CarritoCompra con Operaciones CRUD en Memoria
28public class CarritoCompra {
29 private int idCarrito;
30 private String cliente;
31 private ArrayList<ItemCarrito> items;
32
33 public CarritoCompra(int idCarrito, String cliente) {
34 this.idCarrito = idCarrito;
35 this.cliente = cliente;
36 this.items = new ArrayList<>();
37 }
38
39 public int getIdCarrito() { return idCarrito; }
40 public String getCliente() { return cliente; }
41
42 // [CREATE / UPDATE]: Añadir producto o incrementar si ya existe
43 public void agregarProducto(Producto p, int cantidad) {
44 if (cantidad <= 0 || p.getStock() < cantidad) {
45 System.out.println("❌ Stock insuficiente o cantidad inválida.");
46 return;
47 }
48
49 // Verificar si ya está en el carrito (UPDATE de cantidad)
50 for (ItemCarrito item : items) {
51 if (item.getProducto().getId() == p.getId()) {
52 item.setCantidad(item.getCantidad() + cantidad);
53 p.setStock(p.getStock() - cantidad);
54 System.out.println("✅ Cantidad actualizada en Carrito #" + idCarrito + ": " + item);
55 return;
56 }
57 }
58
59 // Si es nuevo en el carrito (CREATE)
60 items.add(new ItemCarrito(p, cantidad));
61 p.setStock(p.getStock() - cantidad);
62 System.out.println("✅ Producto agregado al Carrito #" + idCarrito + ": " + p.getNombre());
63 }
64
65 // [READ]: Listar contenido del carrito y total
66 public void mostrarCarrito() {
67 System.out.println("
68🛒 ================= CARRITO #" + idCarrito + " (" + cliente + ") =================");
69 if (items.isEmpty()) {
70 System.out.println(" El carrito está vacío.");
71 } else {
72 for (int i = 0; i < items.size(); i++) {
73 System.out.println(" " + (i + 1) + ". " + items.get(i));
74 }
75 System.out.println("------------------------------------------------------------");
76 System.out.println("💰 MONTO TOTAL A PAGAR: $" + String.format("%.2f", calcularTotal()));
77 }
78 System.out.println("============================================================
79");
80 }
81
82 // [UPDATE]: Modificar cantidad de un producto específico
83 public void modificarCantidad(int idProducto, int nuevaCantidad) {
84 for (ItemCarrito item : items) {
85 if (item.getProducto().getId() == idProducto) {
86 if (nuevaCantidad <= 0) {
87 eliminarProducto(idProducto);
88 } else {
89 int diferencia = nuevaCantidad - item.getCantidad();
90 item.getProducto().setStock(item.getProducto().getStock() - diferencia);
91 item.setCantidad(nuevaCantidad);
92 System.out.println("🔄 Cantidad modificada a " + nuevaCantidad + " para " + item.getProducto().getNombre());
93 }
94 return;
95 }
96 }
97 System.out.println("❌ El producto no se encuentra en el carrito.");
98 }
99
100 // [DELETE]: Eliminar un producto del carrito
101 public void eliminarProducto(int idProducto) {
102 items.removeIf(item -> {
103 if (item.getProducto().getId() == idProducto) {
104 item.getProducto().setStock(item.getProducto().getStock() + item.getCantidad()); // Devuelve stock
105 System.out.println("🗑️ Producto " + item.getProducto().getNombre() + " eliminado del Carrito.");
106 return true;
107 }
108 return false;
109 });
110 }
111
112 // Calcular el total de la compra
113 public double calcularTotal() {
114 double total = 0;
115 for (ItemCarrito item : items) {
116 total += item.getSubtotal();
117 }
118 return total;
119 }
120}
4. Creación y Gestión de Múltiples Carritos en el Main
MainTienda.java (Múltiples Carritos en Memoria)
JAVA
1import java.util.ArrayList;
2
3public class MainTienda {
4 public static void main(String[] args) {
5 // 1. Crear Categorías
6 Categoria catTech = new Categoria(1, "Tecnología");
7 Categoria catHogar = new Categoria(2, "Hogar");
8
9 // 2. Crear Catálogo de Productos
10 Producto p1 = new Producto(101, "Laptop Gaming", 1200.00, 10, catTech);
11 Producto p2 = new Producto(102, "Mouse Inalámbrico", 25.50, 50, catTech);
12 Producto p3 = new Producto(103, "Cafetera Espresso", 89.90, 15, catHogar);
13
14 // 3. Gestor de Múltiples Carritos en Memoria RAM
15 ArrayList<CarritoCompra> listaCarritosGlobal = new ArrayList<>();
16
17 // ----------------------------------------------------
18 // CREAR Y OPERAR EN EL CARRITO #1 (Cliente: Ana)
19 // ----------------------------------------------------
20 CarritoCompra carritoAna = new CarritoCompra(1, "Ana Pérez");
21 listaCarritosGlobal.add(carritoAna);
22
23 carritoAna.agregarProducto(p1, 1); // Laptop x1
24 carritoAna.agregarProducto(p2, 2); // Mouse x2
25 carritoAna.mostrarCarrito();
26
27 // Modificar cantidad (UPDATE)
28 carritoAna.modificarCantidad(102, 3); // Cambiar Mouse a x3
29 carritoAna.mostrarCarrito();
30
31 // ----------------------------------------------------
32 // CREAR OTRO CARRITO INDEPENDIENTE #2 (Cliente: Carlos)
33 // ----------------------------------------------------
34 CarritoCompra carritoCarlos = new CarritoCompra(2, "Carlos Gómez");
35 listaCarritosGlobal.add(carritoCarlos);
36
37 carritoCarlos.agregarProducto(p3, 2); // Cafetera x2
38 carritoCarlos.agregarProducto(p2, 1); // Mouse x1
39 carritoCarlos.mostrarCarrito();
40
41 // Eliminar producto (DELETE)
42 carritoCarlos.eliminarProducto(103); // Eliminar Cafetera
43 carritoCarlos.mostrarCarrito();
44
45 // ----------------------------------------------------
46 // LISTAR TODOS LOS CARRITOS ACTIVOS EN LA TIENDA
47 // ----------------------------------------------------
48 System.out.println("🏬 TOTAL DE CARRITOS ACTIVOS EN TIENDA: " + listaCarritosGlobal.size());
49 for (CarritoCompra c : listaCarritosGlobal) {
50 System.out.println("-> Carrito #" + c.getIdCarrito() + " | Cliente: " + c.getCliente() + " | Total: $" + c.calcularTotal());
51 }
52 }
53}
Ponte a prueba
Verifica tu conocimiento sobre el proyecto CRUD en memoria RAM.


