Swift World:设计模式-适配器

我们已经完成了创建模式,并将在本文中介绍结构模式。 从字面上看,结构模式与结构有关。 这意味着如何组织类或实例以形成更大的结构。 我们首先要讨论的是适配器模式。

现实世界中最新的适配器示例是闪电式3.5毫米耳机插孔适配器。 如果我们想在使用防雷连接器的新iPhone 7中重复使用旧耳机,则需要使用此适配器进行连接。

显然,耳机插孔适配器是适配器。 旧的3.5毫米耳机是适配器。 在编程世界中,适配器是我们要重用的老类。 但是其接口与新接口不兼容。 因此,我们需要一个适配器来帮助他们。

我们可以通过两种方式实现适配器模式。 第一个是使用合成的对象适配器。 适配器中有一个Adaptee实例来完成这项工作,如下图和代码告诉我们。

protocol Target { 
func request ()
}
 class Adapter : Target { 
var adaptee: Adaptee
 init (adaptee: Adaptee ) { 
self. adaptee = adaptee
}
 func request () { 
adaptee .specificRequest ()
}
}
 class Adaptee { 
func specificRequest () {
print ("Specific request")
}
}
 // usage 
let adaptee = Adaptee ()
let tar = Adapter (adaptee: adaptee)
tar .request ()

另一个是类适配器,它使用多重继承来连接目标和适配器。

 protocol Target { 
func request()
}
 class Adaptee { 
func specificRequest() {
print("Specific request")
}
}
 class Adapter: Adaptee, Target {s 
func request() {
specificRequest()
}
}
 // usage 
let tar = Adapter()
tar.request()

这就是理论的全部。 在接下来的文章中,我们将在真实的编程世界中带来更多示例。