Jam*_*ham 12 design-patterns class-cluster ios automatic-ref-counting swift
这是一种相对常见的设计模式:
它允许您从init调用中返回子类.
我试图找出使用Swift实现相同功能的最佳方法.
我知道有很好的方法可以用Swift实现同样的功能.但是,我的课程将由现有的Obj-C库初始化,我无法控制.因此它需要以这种方式工作并且可以从Obj-C调用.
任何指针都将非常感激.
我不相信Swift可以直接支持这种模式,因为初始化器不会像在Objective C中那样返回值 - 因此您没有机会返回备用对象实例.
您可以使用类型方法作为对象工厂 - 一个相当人为的例子是 -
class Vehicle
{
var wheels: Int? {
get {
return nil
}
}
class func vehicleFactory(wheels:Int) -> Vehicle
{
var retVal:Vehicle
if (wheels == 4) {
retVal=Car()
}
else if (wheels == 18) {
retVal=Truck()
}
else {
retVal=Vehicle()
}
return retVal
}
}
class Car:Vehicle
{
override var wheels: Int {
get {
return 4
}
}
}
class Truck:Vehicle
{
override var wheels: Int {
get {
return 18
}
}
}
Run Code Online (Sandbox Code Playgroud)
main.swift
let c=Vehicle.vehicleFactory(4) // c is a Car
println(c.wheels) // outputs 4
let t=Vehicle.vehicleFactory(18) // t is a truck
println(t.wheels) // outputs 18
Run Code Online (Sandbox Code Playgroud)