Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when do we need Adapter pattern?

When do we need to go for Adapter pattern? If possible give me a real world example that suits that pattern.

like image 271
brainless Avatar asked Aug 13 '10 15:08

brainless


People also ask

Why do we need adapter design pattern?

The adapter design pattern's purpose is to lay down criteria that make classes work together that could not otherwise because of incompatible interfaces. The intent is to convert the interface of one class into another interface so that it becomes compatible with what the client expects.

Where we can use adapter design pattern?

An Adapter pattern acts as a connector between two incompatible interfaces that otherwise cannot be connected directly. An Adapter wraps an existing class with a new interface so that it becomes compatible with the client's interface.

What is the most common uses of the adapter pattern?

Usage of Adapter pattern: It is used: When an object needs to utilize an existing class with an incompatible interface. When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.

What problem does the adapter pattern solves?

It helps objects with incompatible interfaces to work together.


1 Answers

I worked on a system which needed to interface with external DVRs. For the most part, all DVRs have the same basic functionality: start recording from a certain video source; stop recording; start playback from a certain time; stop playback, etc.

Every DVR manufacturer provided a software library, allowing us to write code to control their device (for sake of this discussion, I'll refer to it as the SDK). Even though every SDK provided APIs for all the basic functionality, none of them were quite the same. Here's a very rough example, but you get the idea:

  • BeginPlayback(DateTime startTime);
  • StartPlayback(long startTimeTicks);
  • Playback(string startDate, string startTime);

Our software needed to be able to interact with all DVRs. So instead of writing horrible switch/cases for each different SDK, we created our own common IDVRController interface, and wrote all of our system code to that interface:

  • Playback(DateTime startTime);

We then wrote a different adapter implementation for each SDK, all of which implemented our IDVRController interface. We used a config file to specify the type of DVR the system would connect to, and a Factory pattern to instantiate the correct implementer of IDVRController for that DVR.

In that way, the adapter pattern made our system code simpler: we always coded to IDVRController. And it allowed us to roll out adapters for new SDKs post-deployment (our Factory used reflection to instantiate the correct IDVRController instance).

like image 75
mikemanne Avatar answered Sep 18 '22 13:09

mikemanne