设计模式-简单工厂模式

简单工厂模式(Simple Factory),又称作静态工厂方法(Static Factory Method)模式,属于创建型模式。在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

设计模式-概述

结构

包含如下角色

  1. Factory 工厂
  2. Product 抽象产品
  3. ConcreteProduct 具体产品

simple-factory-1.png

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
# common.iuml
!define Class(name) class name
!define Class(name,desc) class name as "name\ndesc"
!define Interface(name,desc) interface name as "name\ndesc"


@startuml simple-factory-1
!include common.iuml

Class(Product,"产品") << abstract >>{
+use() : void
}

Class(ConcreteProductA,"产品A"){
+use() : void
}

Class(ConcreteProductB,"产品b"){
+use() : void
}

Class(Factory,"工厂") {
+createProduct(String flag) : Product
}

note as N1
public Product createProduct(String flag){
if (flag == "A"){
return new ConcreteProductA();
} else if (flag == "B"){
return new ConcreteProductB();
}
}
end note

Product <|.. ConcreteProductA
Product <|.. ConcreteProductB
ConcreteProductA <.. Factory
ConcreteProductB <.. Factory
N1 .left. Factory

@enduml

使用时序

simple-factory-2.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@startuml simple-factory-2

actor iMain
participant Factory
participant ConcreteProductA

activate iMain
iMain ->> Factory : --1. createProduction(string) :Product
activate Factory
Factory -->> ConcreteProductA : --2. <<create>>
deactivate Factory
iMain ->> ConcreteProductA : --3. use()
deactivate iMain

@enduml

代码实例

1
2
3
4
5
6
7
8
9
10
11
public class XXXFactory {
public static Object createObject(String flag) {
if ("String".equals(flag)) {
return "hello";
} else if ("Int".equals(flag)) {
return 1;
} else {
return new Object();
}
}
}

使用场景

  • 工厂类创建的对象较少; 否则会导致Factory内部非常复杂, 难以维护, 这不是正确的.
  • 使用者仅仅关系创建对象的参数, 不关心具体的创建过程.

应用

  1. jdk java.text.DateFormat
    1
    2
    3
    DateFormat.getDateInstance();
    DateFormat.getDateInstance(int style);
    DateFormat.getDateInstance(int style, Locale aLocale);
  2. Java加密技术
    1
    2
    KeyGenerator keyGen=KeyGenerator.getInstance("DESede");
    Cipher cp=Cipher.getInstance("DESede");