Repository navigation
Expand file tree
/
Copy pathShapeFactory2.java
More file actions
96 lines (90 loc) · 2.11 KB
/
Copy pathShapeFactory2.java
File metadata and controls
96 lines (90 loc) · 2.11 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//: patterns/ShapeFactory2.java
// Polymorphic factory methods.
import java.util.*;
class BadShapeCreation extends Exception {
BadShapeCreation(String msg) {
super(msg);
}
}
interface Shape {
void draw();
void erase();
}
abstract class ShapeFactory {
protected abstract Shape create();
static Map factories = new HashMap();
static Shape createShape(String id)
throws BadShapeCreation {
if(!factories.containsKey(id)) {
try {
Class.forName(id); // Load dynamically
} catch(ClassNotFoundException e) {
throw new BadShapeCreation(id);
}
// See if it was put in:
if(!factories.containsKey(id))
throw new BadShapeCreation(id);
}
return
((ShapeFactory)factories.get(id)).create();
}
}
class Circle implements Shape {
private Circle() {}
public void draw() {
System.out.println("Circle.draw");
}
public void erase() {
System.out.println("Circle.erase");
}
static class Factory extends ShapeFactory {
@Override
protected Shape create() {
return new Circle();
}
}
static {
ShapeFactory.factories.put(
"Circle", new Circle.Factory());
}
}
class Square implements Shape {
private Square() {}
public void draw() {
System.out.println("Square.draw");
}
public void erase() {
System.out.println("Square.erase");
}
static class Factory extends ShapeFactory {
@Override
protected Shape create() {
return new Square();
}
}
static {
ShapeFactory.factories.put(
"Square", new Square.Factory());
}
}
public class ShapeFactory2 {
public static void main(String args[]) {
String shlist[] = { "Circle", "Square",
"Square", "Circle", "Circle", "Square" };
ArrayList shapes = new ArrayList();
try {
for(int i = 0; i < shlist.length; i++)
shapes.add(
ShapeFactory.createShape(shlist[i]));
} catch(BadShapeCreation e) {
e.printStackTrace();
return;
}
Iterator i = shapes.iterator();
while(i.hasNext()) {
Shape s = (Shape)i.next();
s.draw();
s.erase();
}
}
} ///:~