forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShapeFactory1.java
More file actions
80 lines (75 loc) · 1.7 KB
/
ShapeFactory1.java
File metadata and controls
80 lines (75 loc) · 1.7 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
69
70
71
72
73
74
75
76
77
78
79
80
// patterns/factory/ShapeFactory1.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// A simple static factory method
// {java patterns.factory.ShapeFactory1}
package patterns.factory;
import java.util.*;
import java.util.stream.*;
class BadShapeCreation extends RuntimeException {
BadShapeCreation(String msg) {
super(msg);
}
}
abstract class Shape {
public abstract void draw();
public abstract void erase();
static Shape factory(String type)
throws BadShapeCreation {
switch(type) {
case "Circle": return new Circle();
case "Square": return new Square();
default:
throw new BadShapeCreation(type);
}
}
}
class Circle extends Shape {
Circle() {} // Friendly constructor
@Override
public void draw() {
System.out.println("Circle.draw");
}
@Override
public void erase() {
System.out.println("Circle.erase");
}
}
class Square extends Shape {
Square() {} // Friendly constructor
@Override
public void draw() {
System.out.println("Square.draw");
}
@Override
public void erase() {
System.out.println("Square.erase");
}
}
public class ShapeFactory1 {
public static void main(String[] args) {
List<Shape> shapes = Stream.of(
"Circle", "Square",
"Square", "Circle",
"Circle", "Square")
.map(Shape::factory)
.collect(Collectors.toList());
shapes.forEach(Shape::draw);
shapes.forEach(Shape::erase);
}
}
/* Output:
Circle.draw
Square.draw
Square.draw
Circle.draw
Circle.draw
Square.draw
Circle.erase
Square.erase
Square.erase
Circle.erase
Circle.erase
Square.erase
*/