-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStaticFactory.java
More file actions
44 lines (38 loc) · 961 Bytes
/
StaticFactory.java
File metadata and controls
44 lines (38 loc) · 961 Bytes
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
package com.github.chapter1;
/**
* 静态工厂方法替代构造器
*/
public class StaticFactory {
}
class Father {
private Father() {
}
public static Father newInstance(String type) {
if (type.equals("ChildA")) {
return new ChildA();
} else {
return new ChildB();
}
}
public void getName() {
System.out.println("My name is father");
}
private static class ChildA extends Father {
public void getName() {
System.out.println("My name is child A");
}
}
private static class ChildB extends Father {
public void getName() {
System.out.println("My name is child B");
}
}
}
class Test {
public static void main(String[] args) {
Father father1 = Father.newInstance("ChildA");
father1.getName();
Father father2 = Father.newInstance("ChildB");
father2.getName();
}
}