-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceRepositoryExample.java
More file actions
50 lines (39 loc) · 1.28 KB
/
Copy pathServiceRepositoryExample.java
File metadata and controls
50 lines (39 loc) · 1.28 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
/**
* Day 36 - REST API: Service and Repository Pattern
*/
import java.util.*;
class Product {
int id;
String name;
double price;
Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
}
class ProductRepository {
List<Product> products = new ArrayList<>();
void save(Product p) { products.add(p); }
Product findById(int id) {
return products.stream().filter(p -> p.id == id).findFirst().orElse(null);
}
List<Product> findAll() { return new ArrayList<>(products); }
}
class ProductService {
ProductRepository repo = new ProductRepository();
public void addProduct(Product p) { repo.save(p); }
public Product getProduct(int id) { return repo.findById(id); }
public List<Product> getAllProducts() { return repo.findAll(); }
}
public class ServiceRepositoryExample {
public static void main(String[] args) {
ProductService service = new ProductService();
service.addProduct(new Product(1, "Laptop", 999.99));
service.addProduct(new Product(2, "Phone", 499.99));
System.out.println("All products:");
service.getAllProducts().forEach(p ->
System.out.println(" " + p.name + " - $" + p.price)
);
}
}