Home > Article > Web Front-end > Design Pattern # Adapter Pattern
Over the past few weeks, I have shared some of the trending design patterns, like the PubSub and the Singleton ones. Today, I'm going to share one more article of this series, but please comment below and tell me which design pattern I should cover next!
The Adapter Pattern is a structural design pattern that allows objects with incompatible interfaces to collaborate. It's often used when you want to make existing classes work with others without modifying their source code. This pattern is particularly useful when the interface of an existing class does not match the one you need.
Let's consider a real-life example. You've been tasked to integrate a third-party video player into your application. However, the video player functions differently and has a different method interface than what your application expects. In this case, you could use the Adapter Pattern to create a wrapper class around the video player, making the third-party code compatible with your existing application code.
Here is the code you'd use in this case:
// Adapter class class VideoPlayerAdapter { constructor() { this.externalPlayer = new ThirdPartyVideoPlayer({ // some configuration }); } play() { const video = this.externalPlayer.getVideo(); this.externalPlayer.playVideo(video, { // additional parameters }); } } // Your application code class Application { constructor() { this.videoPlayer = new VideoPlayerAdapter(); } start() { // Play video using your application code this.videoPlayer.play(); } }
Let's break down the code above:
This way, the Application class doesn't need to know anything about how ThirdPartyVideoPlayer works. If you ever need to replace ThirdPartyVideoPlayer with a different library, you only need to write a new adapter — the Application class can stay the same. This is the main benefit of the Adapter pattern: it decouples your application code from the specifics of third-party libraries.
While the Adapter Pattern and the Facade Pattern might seem similar, they serve different purposes and are used in different contexts:
In summary, while both patterns provide a way to work with existing code, the Adapter Pattern focuses on interface compatibility, whereas the Facade Pattern focuses on simplifying the interaction with a complex system.
So, while you are here, let me invite you to participate in our upcoming Superthis August!
This remote event gives you the chance to showcase your skills and creativity by tackling the challenge to transform your virtual interactions with our real-time communication tools. With SuperViz, you stand a chance to win a prize of $5,000.
Register now to receive updates, tips and resources and get ready to hack!
The above is the detailed content of Design Pattern # Adapter Pattern. For more information, please follow other related articles on the PHP Chinese website!