-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAbstracFactory.java
More file actions
110 lines (96 loc) · 1.79 KB
/
AbstracFactory.java
File metadata and controls
110 lines (96 loc) · 1.79 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("Circle");
}
}
class Rectangle implements Shape {
public void draw() {
System.out.println("Rectangle");
}
}
interface Color {
void fill();
}
class Red implements Color {
public void fill() {
System.out.println("Red");
}
}
class Blue implements Color {
public void fill() {
System.out.println("Blue");
}
}
class AbstractFactory {
abstract Shape getShape();
abstract Color getColor();
}
class ShapeFactory extends AbstractFactory {
@override
public Shape getShape(String shape) {
if (shape == null) {
return null;
}
if (shape.equals("Circle")) {
return new Circle();
}
else if (shape.equals("Rectangle")) {
return new Rectangle();
}
return null;
}
@override
Color getColor() {
return null;
}
}
class ColorFactory extends AbstractFactory {
@override
public Color getColor(String color) {
if (color == null) {
return null;
}
if (color.equals("Red")) {
return new Red();
}
else if (color.equals("Blue")) {
return new Blue();
}
return null;
}
@override
Shape getShape() {
return null;
}
}
class FactoryBuilder {
public static AbstractFactory getFactory(String type) {
if (type == null) {
return null;
}
if (type.equals("Shape")) {
return new ShapeFactory();
}
else if (type.equals("Color")) {
return new ColorFactory();
}
return null;
}
}
public class Test {
public static void main(String[] args) {
AbstractFactory f1 = FactoryBuilder.getFactory("Shape");
Shape s1 = f1.getShape("Circle");
Shape s2 = f1.getShape("Rectangle");
AbstractFactory f2 = FactoryBuilder.getFactory("Color");
Color c1 = f2.getColor("Red");
Color c2 = f2.getColor("Blue");
s1.draw();
s2.draw();
c1.fill();
c2.fill();
}
}