【发布时间】:2014-12-17 16:54:44
【问题描述】:
此处编写的 Car 和 Truck 类作为示例,但在编译时程序可能不知道它们。
可能还有更多种类的汽车尚不为人所知
例如,可能会有一个名为法拉利、兰博基尼的特殊级别,它可能会出现在系统不知道的道路上。
我们的目标是编程接口,而不是特定的实现
我们需要做以下类似的事情
- 创建实例
var vehicle: IDrive = Vehicle() vehicle.drive()
我们尝试了一些技术,但如果不强制转换为特定实现就无法使其工作,需要一个独立的解决方案而不需要强制转换为特定实现。
也欢迎任何横向方法,也许我们的方法完全错误,但请记住函数 instantiateAndDrive 必须具有基于 protocol 的参数的约束
给负面选民(又称傻瓜)的注意事项:请提出问题以澄清它是否对您没有意义,或者去给自己买一本“白痴设计模式书”
public protocol IDrive {
func drive()
}
public class Car: IDrive {
public init() {}
public func drive() {}
}
class Truck: IDrive {
public init() {}
public func drive() {}
}
class Test { //our attempts
func instantiateAndDrive(Vehicle:IDrive.Type) {
var vehicle = Vehicle()
vehicle.drive()
}
func instantiateAndDrive2<T:IDrive>(Vehicle: T) {
var vehicle = Vehicle()
vehicle.drive()
}
}
var test = Test()
test.instantiateAndDrive(Car.self)
编辑 - 在 AirSpeed Velocity 的回答之后尝试使用类
public protocol Drivable {
init()
func drive()
}
public class Car: Drivable {
public required init() {}
public func drive() { println("vroom") }
}
public class Truck: Drivable {
public required init() {}
public func drive() { println("brrrrrrm") }
}
class Test {
func instantiateAndDrive(Vehicle:Drivable.Type) {
var vehicle = Vehicle()
vehicle.drive()
}
func instantiateAndDrive2<T:Drivable>(Vehicle: T) {
ver vehicle = Vehicle()
vehicle.drive()
}
}
//var test = Test()
//test.instantiateAndDrive(Car.self)
//test.instantiateAndDrive(Truck.self)
【问题讨论】:
标签: design-patterns swift protocols