工厂模式

工厂模式(Factory Pattern)

工厂模式提供了一种不用暴露创建逻辑来创建对象的方法。它包含两个类型:

  1. factory创建对象
  2. product就是被创建的对象

使用例子

根据求职者来生产求职回信对象

1.定义JobApplicant和Email模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public struct JobApplicant {
public let name: String
public let email: String
public var status: Status
public enum Status {
case new
case interview
case hired
case rejected
}
}
public struct Email {
public let subject: String
public let messageBody: String
public let recipientEmail: String
public let senderEmail: String
}

2.创建工厂结构

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
public struct EmailFactory {
public let senderEmail: String
public func createEmail(to recipient: JobApplicant) -> Email {
switch recipient.status {
case .new:
return Email(
subject: "We Received Your Application",
messageBody: "Thanks for applying for a job here! " +
"You should hear from us in 17-42 business days.",
recipientEmail: recipient.email,
senderEmail: senderEmail)
case .interview:
return Email(
subject: "We Want to Interview You",
messageBody: "Thanks for your resume, \(recipient.name)! " +
"Can you come in for an interview in 30 minutes?",
recipientEmail: recipient.email,
senderEmail: senderEmail)
case .hired:
return Email(
subject: "We Want to Hire You",
messageBody: "Congratulations, \(recipient.name)! " +
"We liked your code, and you smelled nice. We want to offer you a position! Cha-ching! $$$",
recipientEmail: recipient.email,
senderEmail: senderEmail)
case .rejected:
return Email(
subject: "Thanks for Your Application",
messageBody: "Thank you for applying, \(recipient.name). " +
"We have decided to move forward with other candidates. " +
"Please remember to wear pants next time!",
recipientEmail: recipient.email,
senderEmail: senderEmail)
}
}
}

3.使用工厂来创建回信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var jackson = JobApplicant(name: "Jackson Smith",
email: "jackson.smith@example.com",
status: .new)
let emailFactory = EmailFactory(senderEmail: "RaysMinions@RaysCoffeeCo.com")
// New
print(emailFactory.createEmail(to: jackson), "\n")
// Interview
jackson.status = .interview
print(emailFactory.createEmail(to: jackson), "\n")
// Hired
jackson.status = .hired
print(emailFactory.createEmail(to: jackson), "\n")

如果你的对象非常简单,你就不需要使用工厂模式

其他例子

  1. 3种工厂模式:https://www.jianshu.com/p/847af218b1f0
  2. Cocoa中的抽象工厂模式(NSNumber,类簇):http://ibloodline.com/articles/2016/09/06/factory.html
  3. 工厂模式在tableviewCell中的使用:https://juejin.im/post/5b5c0fe3e51d451989055798