Swift Solutions: Adapter Pattern

Tram Ho

In what we hope to be a series, “Swift Solutions” will cover different design patterns, why we use them, and how to deploy them in a Swifty way. The Adapter Pattern is a design pattern that allows objects with similar functionality to work together despite an incompatible interface. It allows integration leading to cleaner code and easier to use. Literally, it modifies an object so that it uses the more familiar APIs

Use Cases

The Adapter Pattern should be used in the following cases:

  • A component that shares similar functionality with existing objects in your application.
  • Although it shares similar functionality, this component has an incompatible interface with other objects in your application.
  • This component is usually from a third-party framework.
  • Cannot (or should not) modify the component’s source code.
  • The component needs to integrate with your application.

The Adapter Pattern allows us to take this foreign object and make it work well with our existing objects. There are two main approaches to achieving this: Swift Extensions and Dedicated Adapter Class. Enough with theory! Let us see what the Adapter Pattern looks like in the practice.

Adapter Pattern: Swift Extension Approach

Swift Extension is an elegant solution for most simple situations.

Here we have a dog and a cat. Both can perform jump (). For now, let’s say we integrate a third-party framework and have an alien animal.

The Adaptee

Some things to note:

  • Our frog object has some of the same functionality as our furry friends.
  • Though it jumps, its interface is different: we have to call the leap () function instead of jump () to get the functionality we want.

The Adapter

Here we integrate our component by implementing the Adapter Pattern. We simply follow Frog to Jumping and create a function that wraps our other objects out. We can now eliminate our frog’s similar behavior without modifying its existing implementation. We simply extend it with a new wrapper function to remove its difference!

Before and After

It will be helpful to see how we work with our objects before and after we modify our frog’s interface.



Adapter Pattern: The Dedicated Adapter Approach

For more complex situations, creating an adapter class can be helpful.

Here we create an adapter class that holds the foreign component in its own property. Frog’s expansion may have had more exposure than we’d like. With dedicated adapter, callers can no longer manipulate frog directly; it can only use anything revealed by FrogAdapter. This allows for better frog packaging, giving us complete control over what is in contact with the caller. And that’s pretty good for both approaches!

Referent from Source: Link

Share the news now

Source : Viblo