我在JAVA中执行类似于Bridge Pattern的操作,DriverType
是协议,需要名为vehicle
的属性为Drivable
对象,Drivable
也是一个协议,并被班级' Car'
protocol Drivable {
var speed: Double { get }
}
protocol DriverType {
var vehicle: Drivable { get }
}
class Car: Drivable {
var speed = 80.0;
var brand = "BMW"
}
class Driver: DriverType {
var vehicle: Car = Car() //Error: Type 'Driver' does not conform to protocol 'DriverType'
// This one works, but I have to downcast the property to 'Car' everytime I use it.
var vehicle: Drivable = Car() //Type 'Driver' does not conform to protocol 'DriverType'
}
当我实施Driver
课程时,将vehicle
属性声明为Car
非常自然。但后来我遇到了编译器认为Driver
不符合DriverType
的问题,即使Car
完全符合Drivable
。
更新:
@Antonio的回答很可靠,但这是我目前所解决的问题,它并不涉及到该类的泛型。
protocol Drivable {
var speed: Double { get }
init()
}
protocol DriverType {
func vehicle() -> Drivable
}
class Car: Drivable {
var speed = 80.0;
var brand = "BMW"
required init() {}
}
class Driver: DriverType {
private var m_vehicle: Car = Car()
func vehicle() -> Drivable {
return m_vehicle
}
// Inside Driver class I use the m_vehicle property directly
}
答案 0 :(得分:1)
我认为编译错误具有误导性。 DriverType
声明任何采用它的类都必须使用vehicle
类型公开Drivable
属性,而不是使用Drivable
类型的类类型的属性。
我会通过使用泛型定义DriverType
协议和Car
类来解决此问题:
protocol Drivable {
var speed: Double { get }
init()
}
protocol DriverType {
typealias T: Drivable
var vehicle: T { get }
}
class Car: Drivable {
var speed = 80.0;
var brand = "BMW"
required init() {}
}
class Driver<T: Drivable>: DriverType {
var vehicle: T = T()
}
这明确指出采用DriverType
的类必须公开vehicle
属性,其类型是采用Drivable
协议的任何类。