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)