Hello everyone, I am fat, after a year of growth, I am not the original me, I will continue to bring you more technical tutorials.

What is the adapter pattern?

Needless to say, the core of the adapter pattern is not the adapter pattern, but the adaptation, why adaptation, which scenarios we need to use adaptation?

First of all, let’s take a hardware example. Before typeC came out, the majority of earphones we saw were round plugs, which were called advanced 3.5mm headphone holes in digital circles. Why must they be round? The answer is, of course, you can make it side, you put the headphone jack into hexagons all nobody tube you, you said unfortunately, scientists have developed a hexagon just plug headphones, ten thousand times better than the traditional headphones sound quality, but the problem appears, hexagonal headphones plug for the market is a kind of brand-new solution, even if you how advanced the technology, Why? Because all mobile phones in the market have round or square headphone holes, there is no hexagon headphone hole at all. But I want to use the new hexagon plug earphone with explosive sound quality.

Attention, focus, make a 3.5 mm interface connection to fit hexagon interface turns, pay attention to the adapter, because of the existence of this tieline, for mobile phone, everything is nothing different, because is plug into the 3.5 mm, but is ably, through the adapter, also is this with tieline, We made the old system work seamlessly with the new technology.

Therefore, the role of the adapter must be to provide a bridge between the old system and the new system, so that the old system can be extended to new functionality without any changes. In the example above, the old system refers to the phone, which we can’t change, the new technology refers to the hexagon headphone plug, and the adapter is the 3.5mm hexagon adapter.

The code field

Actual combat background

Let’s go back to the software level, suppose a company has a set of image processing system is operating, very unfortunately, the system is very complex, and the development extremely is not standard, the document also have no, variable what is what also don’t know, is the code at that time, reconstructing the crematorium, change couldn’t laid hands on him, extreme point, if we change the original code, The original system only supports image processing, but now we need to add video processing and audio processing, but we can’t change the original code, so I want to add these two functions, what should I do? The adapter pattern comes in handy.

We can in the old API and add a bridge between the new system, our application is still call the same method, nothing has changed, but the internal implementation, we have been quietly changed into the new implementation, is similar to tieline, we next deeper through code samples to understand the adapter pattern.

First let’s take a look at the old system about image processing code:

class Image:
    
    def __init__(self, filename) :
        self.filename = filename

    def execute(self) :
        print("Start processing the image.")
Copy the code

Now let’s rewrite two classes that represent the new video and audio processing capabilities:

class Video:

    def __init__(self, filename) :
        self.filename = filename

    def video_processing(self) :
        print("Start processing video")


class Audio:
    
    def __init__(self, filename) :
        self.filename = filename

    def audio_processing(self) :
        print("Start processing audio")
Copy the code

Now, the old system will only call the execute method to execute the task, which is a dead end. There will be some errors in this process. I will change the audio_processing methods to execute. Do you want to call Execute, too? It’s not impossible, but it’s not recommended, and if you have too many of these methods, the system will have too many methods with duplicate names, which can make the messy code even worse

I can’t change the name of the method, so how can I adapt the execute() method call of the old system? Then we need to start writing the adapter.

class Adapter:
    def __init__(self,adapted_methods) :
        self.__dict__.update(adapted_methods)
Copy the code

The __dict__ magic method adds the methods of the new component object to the property dictionary of the adapter object. This allows you to invoke the methods of the new component using the adapter object.

Didn’t? . It seems as simple as that, of course, you can also pass objects in to do some extra processing:

class Adapter:
    def __init__(self,obj,adapted_methods) :
        self.obj = obj
        self.__dict__.update(adapted_methods)

    def __str__(self) :
        # Extra processing, return object information
        return str(self.obj)

Copy the code

We’re still going to go for the humblest version. Now it’s time for our transfer.

audio = Audio('moog')
Adapter(dict(execute=audio.audio_processing)).execute()
Copy the code

Execute () is called, but the audio_processing method is actually executed, so the old system just calls execute(). The internal logic has been quietly replaced with new processing logic.

It’s pretty simple, it’s basically method renaming, and if it’s not a class call, it’s just a simple method call, you can even do that and get the same effect, but it’s not recommended.

synth = Audio('moog')
execute = synth.audio_processing
execute()

Run result
# Start processing audio
Copy the code

No, let’s move on to the summary:

conclusion

Adapter to use, useful, in which can change the project, the reasonable application of adapter pattern to the old system is expanded to become simple, but in the above study, we also found that the adapter pattern gradually looking is not so good, there is no doubt that it will make our program logic chaos, we call the old method, the internal is replaced by the new implementation, It should be audio_processing, but it is execute externally.

If you’re new to the project, there’s a good chance that audio_processing deals with audio, whereas execute doesn’t get anything of value.

If there are too many adapters internally, our code logic will become messy, so it is better to refactor the old project to fit the new interface if possible. If the original code cannot be changed, then the adapter may be a good choice.

Because the hexagon headphones plugged in to support directly to the hexagon on the headphone jack’s cell phone, must be better than the first hexagon hexagon turn into the 3.5 mm headsets through online, plug tieline 3.5 mm to support only 3.5 mm headphone jack phones are much more simple, because I only played 27 before a word is said understand, I typed 51 words with the transfer wires.

Finally, thank you very much for reading this. Your support and attention are the motivation for me to continue to share with high quality.

All of Hanshu’s notes have been uploaded to my Github. Make sure you hit “STAR” ahhhhhhh

Long march always feeling, to a star line

Hanshu development notes

Welcome to like, follow me, have good fruit to eat (funny)