Statement: This series of blog reference "Big Talk design mode", author Geoscience.
Adapter Mode (sometimes also referred to as packaging style or packaging) adapt the interface of a class to what the user expects (the core problem that the adapter pattern solves). an adaptation allows classes that are usually not working together because of incompatible interfaces, by wrapping the class's own interface in an existing class.
Class Diagram:
ready to fit ( Foreignplayer ) Role: The interface rules within the interface rules for this role are inconsistent, but internal calls to the role's method capabilities are required.
Internal Interface ( IPlayer ) Role: This is an abstract role that gives the internal expected interface rules.
Adapter ( Adapter ) Role: by wrapping an internal Adapter object, the adapter interface is converted to a target interface, This role is the core role of the adapter pattern is the key to the problem that the adapter mode solves.
Code:
<?php/** * Created by Phpstorm. * User:jiang * DATE:2015/4/26 * time:12:23 *///-------------Abstract Interface---------------/** abstract athlete * Interface IPlayer */interface iplayer{function Attack (); function Defense ();} /** striker * Class Forward */class Forward implements iplayer{function Attack () {echo "Striker attack <br/>"; } function Defense () {echo "Forward defense <br/>"; }}/** Center * Class Center */class Center implements iplayer{function Attack () {echo "Center attack <br/>"; } function Defense () {echo "Center defense <br/>"; }}//--------------to be adapted-----------/** Yao foreign athlete * Class yaoming */class yaoming{function attack () { echo "Yao Ming offensive <br/>"; } function Defense () {echo "Yao Ming defense <br/>"; }}//------------Adapter--------------/** Adapter * Class Adapter */class Adapter implements iplayer{private $_player; function __construct () {$this->_player=new yaoming (); } function Attack () { $this->_player-> attack (); } function Defense () {$this->_player-> defense (); }}
Client Test Code:
Header ("Content-type:text/html;charset=utf-8");//------------------------prototype mode test code------------------require_ Once "./adapter/adapter.php"; $player 1=new Forward (); echo "forwards on:<br/>"; $player 1->attack (); $player 1-> Defense (), echo "
Applicable scenarios
1 . All the methods to be implemented are specified in the interface.
2 . But to have a specific class that implements this interface, only a few of them are used, and other methods are useless.
Precautions
1 . The class that acts as an adapter role is an abstract class that implements an existing interface
2 . Why use abstract classes:
This class is not instantiated. Instead of acting as an adapter, it provides a common interface for its subclasses, but its subclasses can focus only on where they are interested.
PHP Object-oriented design pattern
PHP design mode-Adapter mode