工厂方法(FactoryMethod)模式的定义:定义一个创建产品对象的工厂接口,将产品对象的实际创建工作推迟到具体子工厂类当中。这满足创建型模式中所要求的“创建与使用相分离”的特点。
工厂方法模式的主要优点有:
• 用户只需要知道具体工厂的名称就可得到所要的产品,无须知道产品的具体创建过程;
• 在系统增加新的产品时只需要添加具体产品类和对应的具体工厂类,无须对原工厂进行任何修改,满足开闭原则;
enum BandLevel {
case expensive
case normal
case cheap
}
class Shoe {
/// 品牌
var band : String
/// 尺码
var size : String
init(band:String, size:String) {
self.band = band
self.size = size
}
func printInfo() {
print("品牌:\(self.band)=尺码:\(self.size)")
}
}
class putianShoesFactory {
func makeShoes(bandLevel:BandLevel) -> Shoe {
switch bandLevel {
case .expensive:
return Shoe(band: "阿迪王", size: "43")
case .normal:
return Shoe(band: "安踏", size: "43")
case .cheap:
return Shoe(band: "耐克", size: "43")
}
}
}
let factory = putianShoesFactory()
factory.makeShoes(bandLevel: .expensive).printInfo()
factory.makeShoes(bandLevel: .normal).printInfo()
factory.makeShoes(bandLevel: .cheap).printInfo()
//品牌:阿迪王=尺码:43
//品牌:安踏=尺码:43
//品牌:耐克=尺码:43