Factory Method
suggest changeIn class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. Wikipedia reference
protocol SenderProtocol
{
func send(package: AnyObject)
}
class Fedex: SenderProtocol
{
func send(package: AnyObject)
{
print("Fedex delivers")
}
}
class RegularPriorityMail: SenderProtocol
{
func send(package: AnyObject)
{
print("Regular Priority Mail delivers")
}
}
// This is our Factory
class DeliverFactory
{
// Returns the instance that handles the task
static func makeSender(isLate: Bool) -> SenderProtocol
{
return isLate ? Fedex() : RegularPriorityMail()
}
}
// Usage:
let package = ["Item 1", "Item 2"]
// Fedex class will handle the delivery
DeliverFactory.makeSender(isLate:true).send(package: package as AnyObject)
// Regular Priority Mail class will handle the delivery
DeliverFactory.makeSender(isLate:false).send(package: package as AnyObject)
Callers then depend on SenderProtocol, not on a concrete class.
A sender handles delivery and exposes send(). That reduces coupling, makes testing easier, and lets you add a new sender without changing the caller.
Within object-oriented design, interfaces provide layers of abstraction that facilitate conceptual explanation of the code and create a barrier preventing dependencies.Wikipedia reference
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents