The adapter pattern (sometimes also called packaging style or packaging) adapts the interface of a class to what the user expects (the core problem to be solved by the adapter pattern). An adaptation allows classes that normally wouldn't work together because of incompatible interfaces to work together by wrapping the class's own interface in an existing class.
Class diagram:
To be adapted (ForeignPlayer) role: The internal interface rules of this role are inconsistent, but the method functions of this role need to be called internally.
Internal interface (IPlayer) role: This is an abstract role that gives the internal expected interface rules.
Adapter role: By packaging an Adapter object internally, the interface to be adapted is converted into a target interface. This role is the core role of the adapter pattern and the key to the problems solved by the adapter pattern.
Code:
<!--?php /** * Created by PhpStorm. * User: Jiang * Date: 2015/4/26 * Time: 12:23 */ //-------------抽象接口--------------- /**抽象运动员 * Interface IPlayer */ interface IPlayer { function Attack(); function Defense(); } /**前锋 * Class Forward */ class Forward implements IPlayer { function Attack() { echo 前锋攻击<br/-->; } function Defense() { echo 前锋防御 ; } } /**中锋 * Class Center */ class Center implements IPlayer { function Attack() { echo 中锋攻击 ; } function Defense() { echo 中锋防御 ; } } //--------------待适配对象----------- /**姚明 外籍运动员 * Class Yaoming */ class Yaoming { function 进攻() { echo 姚明进攻 ; } function 防御() { echo 姚明防御 ; } } //------------适配器-------------- /**适配器 * Class Adapter */ class Adapter implements IPlayer { private $_player; function __construct() { $this->_player=new Yaoming(); } function Attack() { $this->_player->进攻(); } function Defense() { $this->_player->防御(); } }
header(Content-Type:text/html;charset=utf-8); //------------------------原型模式测试代码------------------ require_once ./Adapter/Adapter.php; $player1=new Forward(); echo 前锋上场: ; $player1->Attack(); $player1->Defense(); echo
Applicable scenarios
1. The interface specifies all methods to be implemented
2. But to have a concrete class that implements this interface, only a few of the methods are used, and the other methods are useless.
Notes
1. The class that acts as an adapter is an abstract class that implements an existing interface
2. Why use abstract classes:
This class should not be instantiated. Acting only as an adapter provides a common interface for its subclasses, but its subclasses can only focus on areas of interest.