search
HomeBackend DevelopmentPHP TutorialObject-oriented advanced design pattern: Adapter pattern

Object-oriented advanced design pattern: Adapter pattern

May 20, 2017 pm 02:35 PM
Design Patternsadapter modeobject-oriented

What is the adapter pattern?

The adapter pattern simply adapts the interface of an object to the interface expected by another object.

Adapter pattern application problems and solutions

In your application, you may use a working code base that is architecturally reliable and stable. But we often add new functionality that requires existing objects to be used in a different way than how they were originally designed. At this point, the obstacle may simply be that the new feature needs a different name. In more complex scenarios, an obstacle may also be that the new functionality requires slightly different behavior than the original object.

In response to the above problems, the solution we adopted is to use the adapter pattern to build another object. This Adapter object acts as an intermediary between the original application and the new functionality. The adapter pattern defines new interfaces for existing objects to match the requirements of new objects.

Question

Assume that the functions of the Alipay payment class are as follows:

/** 
 * 支付宝支付类 
 */  
class Alipay  
{  
    public function sendPayment()  
    {  
        echo '使用支付宝支付。';  
    }  
}  
  
// 客户端代码  
$alipay = new Alipay();  
$alipay->sendPayment();

We directly instantiate the Alipay class to complete the payment function. Such client code may a lot of.

After a period of time, what will happen if Alipay’s Alipay class is upgraded and the method name changes from sendPayment() to goPayment()?

All client code that uses sendPayment() must be changed.

If the Alipay class is frequently upgraded, or the client is used in many places, this will be a huge workload.

Solution

Now we use the adapter pattern to solve it.

We add an intermediate class, that is, the adapter class, between the client and the Alipay class to convert the original Alipay into the form required by the client.

In order to allow the client to call a unified class method, we first define an adapter interface:

/** 
 * 适配器接口,所有的支付适配器都需实现这个接口。 
 * 不管第三方支付实现方式如何,对于客户端来说,都 
 * 用pay()方法完成支付 
 */  
interface PayAdapter  
{  
    public function pay();  
}

Because we have no control over the Alipay class, and it may be updated frequently, we do not modify it Make any changes.

We create a new AlipayAdapter adapter class and convert Alipay's payment function in pay(), as follows:

/** 
 * 支付宝适配器 
 */  
class AlipayAdapter implements PayAdapter  
{  
    public function pay()  
    {  
        // 实例化Alipay类,并用Alipay的方法实现支付  
        $alipay = new Alipay();  
        $alipay->sendPayment();  
    }  
}

Client usage:

// 客户端代码  
$alipay = new AlipayAdapter();  
// 用pay()方法实现支付  
$alipay->pay();

In this way, when Alipay's If the payment method changes, you only need to modify the AlipayAdapter class.

Adapting new classes

With adapters, expansion becomes easier.

Continuing with the above example, on the basis of Alipay, we will add WeChat payment. It is different from Alipay's payment method and must be paid by scanning the QR code.

In this case, you should also use an adapter instead of directly using WeChat’s payment function.

The code is as follows:

/** 
 * 微信支付类 
 */  
class WechatPay  
{  
    public function scan()  
    {  
        echo '扫描二维码后,';  
    }  
  
    public function doPay()  
    {  
        echo '使用微信支付';  
    }  
}  
  
/** 
 * 微信支付适配器 
 */  
class WechatPayAdapter implements PayAdapter  
{  
    public function pay()  
    {  
        // 实例化WechatPay类,并用WechatPay的方法实现支付。  
        // 注意,微信支付的方式和支付宝的支付方式不一样,但是  
        // 适配之后,他们都能用pay()来实现支付功能。  
        $wechatPay = new WechatPay();  
        $wechatPay->scan();  
        $wechatPay->doPay();  
    }  
}

Client usage:

// 客户端代码  
$wechat = new WechatPayAdapter();  
// 也是用pay()方法实现支付  
$wechat->pay();

This is the extended feature of the adapter.

We created a method for handling third-party classes (Alipay, WeChat Pay).

If their APIs change, we only need to modify the adapter class that the client depends on. , without modifying or exposing the third-party class itself.

UML diagram

The code of the above adapter pattern corresponds to UML as follows:

Object-oriented advanced design pattern: Adapter pattern

Summary

Large applications will continue to add new libraries and new APIs.

In order to avoid problems caused by their changes, they should be packaged in the adapter pattern to provide a unified reference method for the application.

It will make our code more structured and easier to manage and expand.

The above is the detailed content of Object-oriented advanced design pattern: Adapter pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools