适配器模式 Adapter
现实中的适配器,比如 Type-C 18W 手机充电器(适配器)把高电压转换为低电压,因为手机是需要 9V 电压、2A 电流,而我们的家庭电压是 220V,我们就需要使用适配器,让这个 220 V “假装”是 9V 的电压且拥有 2A 电流,那么手机就可以接受这个外界加入的电力,而且这样的 9 V 2A 是一个标准,若是换了一个适配器来,只要符合 9V 2A 标准的输出,我这个手机就可以接受,而不需纠结于适配器的输入具体是 220 V 还是 还是 110 V 还是其他。
在这个例子中,要适配的对象其实是那个 9V 2A,适配器继承了 “9V 2A”,持有了电压转换装置,将新的未知的输入适配到 9V 2A。而我们抽象的适配器,就是使用一个新的对象,既持有新对象(包括新特征),又长得像我们要适配的对象。
适配器模式的实现:
A class called ‘A’ needs to disguise as another class called ‘B’, create a new adapter to extend the target class B and then insert the class A into the adapter, override the methods from the class B in the adapter. So we can use the adapter which has new features from A, just like we are using class B(The adapter extends from class B).
类 A 想要适配类 B,首先使用一个适配器继承类 B ,把类 A 注入适配器,在适配器里面重写需 要模仿的类 B 的方法。最后,在需要用 A 替换 B 的地方,传递一个适配器即可,因为它既具有 A 的性质,又具有 B 的方法,它继承自 B ,可以当作 B 来调用。
class Bike {
var name = "deafult"
func go() {
print("Bike Go")
}
func addWheel() {
print("Add wheel for\(name)")
}
}
class WaterBike {
var weight = 0
func floating() {
print("The water bike floating on the water")
}
}
// now the water bike adapt the bike, inherit the target(Bike) that be disguised.
class WaterBikeAdapter: Bike {
var waterBike: WaterBike?
init(waterBike: WaterBike) {
self.waterBike = waterBike // inject the waterBike(which want to disguise as other)
}
override func go() {
print("Now it's the water bike go")
}
}
func someThingGo(bike: Bike) {
bike.go()
}
// This mode make the "WaterBike" to disguise as a "Bike"
let waterBikeAdapter = WaterBikeAdapter(waterBike: WaterBike()) // The adapter has a waterBike and has the method of bike.
someThingGo(bike: waterBikeAdapter) // Now it can use as a bike.
代码中的划水自行车适配器继承自自行车,持有一个划水自行车(拥有了划水自行车的功能)。在保留原自行车特征(可以跑起来)的同时,拓展自行车的业务功能(具有在水上浮的能力)。因为泛型,水上自行车仍是可以作为普通自行车来使用。