Junior — Middle
Can you explain the concept of abstract factory and its purpose in design patterns?
sobes.tech AI
Answer from AI
Abstract factory is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.
The purpose of the pattern is to ensure the creation of objects that work together, hiding the details of their specific implementation. This is useful when the system should be independent of the way the products are created, composed, and represented.
Example: In an iOS application, you can use an abstract factory to create UI components that look different on iOS and macOS but have the same interface.
protocol Button {
func render()
}
class iOSButton: Button {
func render() {
print("Render iOS style button")
}
}
class MacOSButton: Button {
func render() {
print("Render macOS style button")
}
}
protocol UIFactory {
func createButton() -> Button
}
class iOSFactory: UIFactory {
func createButton() -> Button {
return iOSButton()
}
}
class MacOSFactory: UIFactory {
func createButton() -> Button {
return MacOSButton()
}
}
// Usage
let factory: UIFactory = iOSFactory()
let button = factory.createButton()
button.render() // Render iOS style button