工厂设计模式,用于封装遵循特定公共接口的实体的实现细节。
下面是一个示例(一个生产水果的工厂):
enum FruitType {
case apple, orange
}
protocol Fruit {
var name: String { get }
}
struct Apple: Fruit {
let name = "Apple"
}
struct Orange: Fruit {
let name = "Orange"
}
class FruitFactory {
static let shared = FruitFactory()
private init() { }
func makeFruit(ofType type: FruitType) -> Fruit {
switch type {
case .apple:
return Apple()
case .orange:
return Orange()
}
}
}
使用方法:
let apple = FruitFactory.shared.makeFruit(ofType: .apple)
let orange = FruitFactory.shared.makeFruit(ofType: .orange)
这样,根据传入类型,就可以获得某种水果。用户完全不用关心具体实现细节。











网友评论