<?php
#将一个类的接口换成客户希望的另外一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
abstract class Player{
protected $name;
function __construct($name){
$this->name= $name;
}
abstract function Attack();
abstract function Defense();
}
//前锋
class Forwards extends Player
{
public function __construct($name){
$this->name= $name;
}
public function Attack(){
echo "前锋".$name."进攻";
}
public function Defense(){
echo "前锋".$this->name."防守";
}
}
//中锋
class Center extends Player{
public function __construct($name){
$this->name= $name;
}
public function Attack(){
echo "中锋".$this->name."进攻";
}
public function Defense(){
echo "中锋".$this->name."防守";
}
}
//外籍中锋
class ForeignCenter{
protected $name;
public function __get($name){
return $this->$name;
}
public function __set($name,$val){
$this->$name = $val;
}
public function gongji(){
echo "中锋".$this->name."进攻";
}
public function fangshou(){
echo "中锋".$this->name."防守";
}
}
//后卫
class Guards extends Player{
public function __construct($name){
$this->name= $name;
}
public function Attack(){
echo "后卫".$this->name."进攻";
}
public function Defense(){
echo "后卫".$this->name."防守";
}
}
class adapter extends Player{
public $adapter;
//$this->adapter = new ForeignCenter(); 报错
public function __construct($name){
//var_dump($name);die;
$this->adapter = new ForeignCenter();
$this->adapter->name = $name;
}
//攻击
public function Attack(){
$this->adapter->gongji();
}
//防守
public function Defense(){
$this->adapter->fangshou();
}
}
//客户段代码
$F = new Forwards("巴蒂尔");
$F->Attack();
$G = new Guards("麦克格雷迪");
$G->Attack();
/*由于姚明一开始不知道Attack与Defense的中文意思,所以需要适配器
$ym = new Center("姚明");
$ym->Attack();
$ym->Defense(); */
//适配器翻译过后代码
$ym = new adapter('姚明');
$ym->Attack();
$ym->Defense();
?>