Swift World: Design Patterns — Adapter

Peng
Peng
Mar 13, 2017 · 2 min read

We have finished creational patterns and will introduce structural patterns from this article. Literally, structural patterns are about structure. It means how to organize classes or instances to form larger structures. The first we will talk about is adapter pattern.

The latest adapter example in real world is lightning to 3.5 mm headphone Jack adapter. If we want to reuse old headphone with our new iPhone 7 which uses lightning connector, we need this adapter to connect them.

Image for post
Image for post

Obviously, the headphone jack adapter is adapter. The old 3.5 mm headphone is adaptee. In the programming world, the adaptee is old class we want to reuse. But its interface is not compatible with new interface. So we need an adapter to help them.

We can implement adapter pattern in two ways. The first one is object adapter which uses composition. There is an adaptee instance in adapter to do the job like the following figure and code tell us.

Image for post
Image for post
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()

The other one is class adapter which uses multiple inheritance to connect target and adaptee.

Image for post
Image for post
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()

This is all about the theory. In next articles, we will bring more examples in real programming world.

Thanks for your time. Please clap to get this article seen by more people. Please follow me by clicking Follow. As a passionate iOS developer, blogger and open source contributor, I’m also active on Twitter and GitHub.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store