forked from emreozdil/Swift-Daily-Tips
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFactoryPattern.swift
45 lines (38 loc) · 1.1 KB
/
FactoryPattern.swift
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
43
44
45
// Factory Pattern
// Factory pattern can come in handy when you want to reduce the dependency of a class
// on other classes. On the other hand, it encapsulates the object creation process
// and users can simply pass in parameters to a generic factory class without knowing
// how the objects are actually being created. Also it gives you a clean code.
protocol Human {
var name : String {get set}
func run()
func eat()
func sleep()
}
class Soldier: Human {
//...
}
class Civilian: Human {
//...
}
enum HumanType {
case soldier
case civilian
}
class HumanFactory {
static let shared = HumanFactory()
func getHuman(type: HumanType, name: String) -> Human {
switch type {
case .soldier:
return Soldier(soldierName: name)
case .civilian:
return Civilian(civilianName: name)
}
}
}
let soldier = HumanFactory.shared.getHuman(type: .soldier, name: "Jay")
soldier.sleep()
//soldider Jay is sleeping
let civilian = HumanFactory.shared.getHuman(type: .civilian, name: "Saman")
civilian.run()
//Saman is running