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.
Let’s begin by creating a protocol (You can achieve the same with a super class too but I like protocol as it enforces certain rules to the classes that are confirming). If you don’t know protocol, then please go refer my article on the topic.
protocol Human { var name : String {get set} func run()
func eat()
func sleep()}
Since we have our protocol ready let’s create two classes named Soldier
and Civilian
.
class Soldier{}class Civilian{}
Now it’s time to conform to the protocol Human
to these classes and implement the methods.
class Soldier : Human{ var name: String init(SoldierName soldiername : String) {
self.name = soldiername
} func run() {
print("soldier \(name) is running")…