
//abstract factory
protocol IFactory {
func createA() -> IProductA
func createB() -> IProductB
}
//concrete factory 1
class Factory1: IFactory {
func createA() -> IProductA {
return ProductA1()
}
func createB() -> IProductB {
return ProductB1()
}
}
//concrete factory 2
class Factory2: IFactory {
func createA() -> IProductA {
return ProductA2()
}
func createB() -> IProductB {
return ProductB2()
}
}
//abstract product A
protocol IProductA {
func testA()
}
//abstract product B
protocol IProductB {
func testB()
}
//concrete product A1
class ProductA1: IProductA {
func testA() {
print("test A1")
}
}
//concrete product A2
class ProductA2: IProductA {
func testA() {
print("test A2")
}
}
//concrete product B1
class ProductB1: IProductB {
func testB() {
print("test B1")
}
}
//concrete product B2
class ProductB2: IProductB {
func testB() {
print("test B2")
}
}
//client code
func testFactory(_ factory: IFactory) {
let productA = factory.createA()
let productB = factory.createB()
productA.testA()
productB.testB()
}
testFactory(Factory1())
//printed: test A1
// test B1
testFactory(Factory2())
//printed: test A2
// test B2
| Provides an interface for creating families of objects whose interfaces are known but concrete classes are not. |