Repository navigation
Expand file tree
/
Copy pathFactoryMain.java
More file actions
68 lines (55 loc) · 1.77 KB
/
Copy pathFactoryMain.java
File metadata and controls
68 lines (55 loc) · 1.77 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
package com.brianway.learning.java8.effective.tech;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
/**
* 工厂模式
*/
public class FactoryMain {
public static void main(String[] args) {
Product p1 = ProductFactory.createProduct("loan");
p1.printClassName();
// with lambdas
Supplier<Product> loanSupplier = Loan::new;
Product p2 = loanSupplier.get();
p2.printClassName();
Product p3 = ProductFactory.createProductLambda("loan");
p3.printClassName();
}
static private class ProductFactory {
public static Product createProduct(String name) {
switch (name) {
case "loan":
return new Loan();
case "stock":
return new Stock();
case "bond":
return new Bond();
default:
throw new RuntimeException("No such product " + name);
}
}
public static Product createProductLambda(String name) {
Supplier<Product> p = map.get(name);
if (p != null) return p.get();
throw new RuntimeException("No such product " + name);
}
}
private interface Product {
default void printClassName() {
System.out.println(getClass().getSimpleName());
}
}
static private class Loan implements Product {
}
static private class Stock implements Product {
}
static private class Bond implements Product {
}
final static private Map<String, Supplier<Product>> map = new HashMap<>();
static {
map.put("loan", Loan::new);
map.put("stock", Stock::new);
map.put("bond", Bond::new);
}
}