-
Notifications
You must be signed in to change notification settings - Fork 1
/
factoryMethod.java
50 lines (39 loc) · 1003 Bytes
/
factoryMethod.java
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
interface Worker {
void work();
}
interface WorkerFactory {
Worker createWorker();
}
class Worker1Factory implements WorkerFactory {
@Override
public Worker createWorker() {
return new Worker1();
}
}
class Worker2Factory implements WorkerFactory {
@Override
public Worker createWorker() {
return new Worker2();
}
}
class Worker1 implements Worker {
@Override
public void work() {
System.out.println("work work work");
}
}
class Worker2 implements Worker {
@Override
public void work() {
System.out.println("work work work");
}
}
public class Main {
public static void main(String[] args){
WorkerFactory workerFactory = new Worker1Factory(); /* 如果要更換其他工廠的worker,只需要更換這一行的實體類別 */
Worker worker1 = workerFactory.createWorker();
Worker worker2 = workerFactory.createWorker();
worker1.work();
worker2.work();
}
}