【创建型】工厂方法模式详解
J.K Apr 5, 2013 2013-04-05T22:38:00+08:00
Apr 11, 2021 2021-04-11T21:54:27+08:00 3 min
【创建型】工厂方法模式
定义
1
2
3
4
5
6
7
8
9
10
| 定义:一抽象产品类派生出多个具体产品类;一抽象工厂类派生出多个具体工厂类;每个具体工厂类只能创建一个具体产品类的实例。
工厂方法模式是简单工厂模式的升级版
工厂方法模式有四个要素:
1.产品接口,产品接口里定义产品的相关动作,产品接口里的定义直接决定代码的稳定性;
2.产品实现,产品实现决定了产品的具体的动作;
3.工厂接口,工厂接口是工厂方法的核心,它与调用方直接耦合来调用产品实现;
3.工厂实现,工厂实现负责如何实例化产品类,每个具体工厂实例化一具体产品类;
|
UML图
1
2
3
4
5
6
7
8
9
10
| _ _ _ _ _ _ _ _ _ _ _ _
| | | |
| IFactory | | IProduct |
|_ _ _ _ _ _| |_ _ _ _ _ _|
↑ ↑
| |
_ _ _|_ _ _ _ _ _|_ _ _
| | | |
| Factory |----→| Product |
|_ _ _ _ _ _| |_ _ _ _ _ _|
|
代码
1
2
3
4
5
| public interface Product{
public void printName();
}
|
1
2
3
4
| public interface Factory{
public Product createProduct();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| public class ProductA implements Product{
public void printName(){
System.out.println("I'm product of A.");
}
} ---
public class ProductB implements Product{
public void printName(){
System.out.println("I'm product of B.");
}
}
|
1
2
3
4
5
6
7
| public class FactoryX implements Factory{
public Product createProduct(){
return new ProductA();
}
}
|
1
2
3
4
5
6
7
| public class FactoryY implements Factory{
public Product createProduct(){
return new ProductB();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| public class Client{
public static void main(String[] args){
Factory xFactory = new FactoryX();
xFactory.createProduct.printName();
Factory yFactory = new FactoryY();
yfactory.createProduct.printName();
}
}
运行结果:
I'm product of A.
I'm product of B.
-----------------
|
应用
JDK中java.lang.String/Boolean/Long/Double/Float等类中valueOf()就是工厂方法模式的的应用:
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
| package java.lang;
import java.io.ObjectStreamField;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
......
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
public static String valueOf(char data[]) {
return new String(data);
}
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
......
}
|
This post is licensed under
CC BY 4.0 by the author.