Abstract Factory 抽象工厂
Base on the factory method, add an abstract factory. We can call the same abstract factory method to create different mode’s product. If we want to create another mode’s product, we need to change the concrete factory.
基于工厂方法模式,我们添加了一个抽象工厂协议,其它具体的工厂来实现这个工厂协议。从而我们可以调用同一个抽象工厂方法来创建不同模式的相似产品(比如 WinButton 和 MacButton)。如果想要切换模式,我们需要切换到另外一种具体的工厂实现。
// Abstract factory
protocol GUIFactory {
func createButton() -> Button
func createCheckBox() -> CheckBox
}
// Concrete factory
class WinGUIFactory: GUIFactory {
func createButton() -> Button {
var btn = WinButton()
return btn
}
func createCheckBox() -> CheckBox {
var box = WinCheckBox()
return box
}
}
// Concrete factory
class MacGUIFactory: GUIFactory {
func createButton() -> Button {
var btn = MacButton()
return btn
}
func createCheckBox() -> CheckBox {
var box = MacCheckBox()
return box
}
}
// Abstract product
protocol Button {
func click()
}
// Abstract product
protocol CheckBox {
func render()
}
// Concrete product
class WinButton: Button {
func click() {
print("Win click button")
}
}
// Concrete product
class WinCheckBox: CheckBox {
func render() {
print("Here the win render checkBox")
}
}
// Concrete product
class MacButton: Button {
func click() {
print("Mac click button")
}
}
// Concrete product
class MacCheckBox: CheckBox {
func render() {
print("Here the mac render checkBox")
}
}
class App {
var factory: GUIFactory
init(factory: GUIFactory) {
self.factory = factory
}
func someOperation() {
var checkBox = factory.createCheckBox()
checkBox.render()
}
}
let factory = WinGUIFactory()
let app = App(factory: factory) // The mode is choosen now, and the behavior in the app is specific.
let button = app.factory.createButton();
button.click()
app.someOperation()