1, 工厂方法,抽象工厂,简单工厂的区别和联系?
工厂与工厂方法,较简单
工厂方法中,给一些描述信息,返回具体的对象
描述信息,就是传参,说一下啥情况
// 工厂,可以方便的创建对象
public class AnnotationFactory {
// 工厂方法,返回一个具体的对象
public func createBusinessMapViewModel(for business: YLPBusiness) -> BusinessMapViewModel? {
guard let yelpCoordinate = business.location.coordinate else {
return nil
}
let coordinate = CLLocationCoordinate2D(latitude: yelpCoordinate.latitude,
longitude: yelpCoordinate.longitude)
let name = business.name
let rating = business.rating
let image: UIImage
switch rating {
case 3.0..<3.5:
image = UIImage(named: "bad")!
case 3.5..<4.0:
image = UIImage(named: "meh")!
default:
image = UIImage(named: "bad")!
}
return BusinessMapViewModel(coordinate: coordinate,
image: image,
name: name,
rating: rating)
}
}
抽象工厂,更加灵活,包含一组工厂方法。
一般,我们需要一组关联性强的对象时,使用抽象工厂
例子:
工厂 A 和 B, 遵守抽象工厂协议,
( 也可以继承自抽象工厂类 )
具体类工厂 A ( concrete class),提供安卓平台的按钮和图片,
具体类工厂 B ,提供 iOS 平台的按钮和图片,