forked from anxpp/JavaDesignPattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleFactory.java
More file actions
69 lines (59 loc) · 1.42 KB
/
Copy pathSimpleFactory.java
File metadata and controls
69 lines (59 loc) · 1.42 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
package com.java.designpattern.simplefactory;
import java.util.HashMap;
//演示简单工厂
public class SimpleFactory {
public static void main(String args[]) throws Exception {
Factory factory = new Factory();
factory.produce("A").run();
factory.produce("B").run();
factory.produce("C").run();
}
}
// 抽象产品
interface IProduct {
void run();
}
// 具体产品 A
class ProductA implements IProduct {
@Override
public void run() {
System.out.println("产品 A");
}
}
// 具体产品 B
class ProductB implements IProduct {
@Override
public void run() {
System.out.println("产品 B");
}
}
// 具体产品 C
class ProductC implements IProduct {
public void run() {
System.out.println("产品 C");
}
}
//工厂
class Factory {
/*
IProduct produce(String product) throws Exception{
if(product.equals("A"))
return new ProductA();
else if(product.equals("B"))
return new ProductB();
throw new Exception("No Such Class");
}
*/
IProduct produce(String product) throws Exception {
switch (product) {
case "A":
return new ProductA();
case "B":
return new ProductB();
case "C":
return new ProductC();
default:
return null;
}
}
}