工厂模式

……

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
package org.sang.plugins.shejimoshi;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class Factory {
final static Map<String, Supplier<Shape>> map = new HashMap<>();
static {
map.put("CIRCLE", Circle::new);
map.put("RECTANGLE", Rectangle::new);
}
public Shape getShape(String shapeType){
Supplier<Shape> shape = map.get(shapeType.toUpperCase());
if(shape != null) {
return shape.get();
}
throw new IllegalArgumentException("No such shape " + shapeType.toUpperCase());
}



public static void main(String[] args) {
Supplier<Factory> shapeFactory = Factory::new;
//call draw method of circle
shapeFactory.get().getShape("circle").draw();
//call draw method of Rectangle
shapeFactory.get().getShape("rectangle").draw();
}
}



interface Shape {
void draw();
}

class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}