1. 简单工厂模式
- 一个工厂类
- 内部用 switch case 创建不同对象
1 import UIKit
2
3 protocol Service {
4 var url: URL { get }
5 }
6
7 // dev阶段
8 class StagingService: Service {
9 var url: URL { return URL(string: "https://dev.localhost/")! }
10 }
11
12 // product阶段
13 class ProductionService: Service {
14 var url: URL { return URL(string: "https://live.localhost/")! }
15 }
16
17 class EnvironmentFactory {
18 enum Environment {
19 case staging
20 case production
21 }
22
23 func create(_ environment:Environment) -> Service{
24 switch environment {
25 case .staging:
26 return StagingService()
27 case .production:
28 return ProductionService()
29 }
30 }
31 }
32
33 let env = EnvironmentFactory()
34 let serv = env.create(.production)
35 print(serv.url) //https://live.localhost/
2. 工厂方法模式
- 多个 (解耦的) 工厂类
- 每个工厂方法创建一个实例
1 import UIKit
2
3 protocol Service {
4 var url: URL { get }
5 }
6
7 protocol ServiceFactory{
8 func create() -> Service
9 }
10
11 // dev阶段
12 class StagingService: Service {
13 var url: URL { return URL(string: "https://dev.localhost/")! }
14 }
15
16 // product阶段
17 class ProductionService: Service {
18 var url: URL { return URL(string: "https://live.localhost/")! }
19 }
20
21 // dev 工厂类
22 class StagingServiceFactory: ServiceFactory{
23 func create() -> Service {
24 return StagingService()
25 }
26 }
27
28 // production 工厂类
29 class ProductionServiceFactory: ServiceFactory{
30 func create() -> Service {
31 return ProductionService()
32 }
33 }
34
35 let serv = ProductionServiceFactory().create()
36 print(serv.url)
3. 抽象工厂模式
1 import UIKit
2
3 // 服务协议
4 protocol ServiceFactory {
5 // 创建一个服务
6 func create() -> Service
7 }
8
9 protocol Service {
10 var url: URL { get }
11 }
12
13 // dev阶段
14 class StagingService: Service {
15 var url: URL { return URL(string: "https://dev.localhost/")! }
16 }
17
18 class StagingServiceFactory: ServiceFactory {
19 // dev工厂就是创建一个dev的服务
20 func create() -> Service {
21 return StagingService()
22 }
23 }
24
25 // product阶段
26 class ProductionService: Service {
27 var url: URL { return URL(string: "https://live.localhost/")! }
28 }
29
30 class ProductionServiceFactory: ServiceFactory {
31 // product工厂就是创建一个product的服务
32 func create() -> Service {
33 return ProductionService()
34 }
35 }
36
37 // 抽象工厂
38 class AppServiceFactory: ServiceFactory {
39
40 enum Environment {
41 case production
42 case staging
43 }
44
45 var env: Environment
46
47 init(env: Environment) {
48 self.env = env
49 }
50
51 func create() -> Service {
52 switch self.env {
53 case .production:
54 return ProductionServiceFactory().create()
55 case .staging:
56 return StagingServiceFactory().create()
57 }
58 }
59 }
60
61 let factory = AppServiceFactory(env: .production)
62 let service = factory.create()
63 print(service.url)