####PHP适配器模式 #####类适配器
类适配器设计模式使用继承
类适配器会被适配者继承功能,需要重新编写的代码较少
/**
* Created by PhpStorm.
* User: gewenrui
* Date: 16/3/8
* Time: 下午8:18
*/
//创建一个美元类
class DollarCalc{
private $dollar;
private $product;
private $service;
public $rate = 1;
public function requestCalc($productNow,$serviceNow){
$this->product = $productNow;
$this->service = $serviceNow;
$this->dollar = $this->product + $this->service;
return $this->requestTotal();
}
public function requestTotal(){
$this->dollar *= $this->rate;
return $this->dollar;
}
}
//创建一个欧元类
class EuroCalc{
private $euro;
private $product;
private $service;
public $rate = 1;
public function requestCalc($productNow,$serviceNow){
$this->product = $productNow;
$this->service = $serviceNow;
$this->euro = $this->product + $this->service;
return $this->requestTotal();
}
public function requestTotal(){
$this->euro *= $this->rate;
return $this->euro;
}
}
//类适配器的接口
interface ITarget{
function requester();
}
//创建一个欧元适配器继承欧元类并实现接口
class EuroAdapter extends EuroCalc implements ITarget{
public function __construct()
{
$this->requester();
}
//实现接口的方法
public function requester()
{
$this->rate =.811;
return $this->rate;
}
}
class Client{
private $requestNow;
private $dollarRequest;
public function __construct()
{
//创建一个欧元适配器
$this->requestNow = new EuroAdapter();
$this->dollarRequest = new DollarCalc();
$euro = "1";
//将对象传入适配器类 用接口类型来约束
echo "Euro:".$this->makeAdapterRequest($this->requestNow);
echo "Dollar".$this->makeDollarRequest($this->dollarRequest);
}
private function makeAdapterRequest(ITarget $req){
return $req->requestCalc(4,50);
}
private function makeDollarRequest(DollarCalc $req){
return $req->requestCalc(40,50);
}
}
$data = new Client();
#####对象适配器
在对象适配器模式中,适配器参与者使用适配者,并实现Target接口
/**
* Created by PhpStorm.
* User: gewenrui
* Date: 16/3/9
* Time: 上午7:30
*/
interface IFormat{
public function formatCss();
}
class Desktop implements IFormat{
public function formatCss()
{
// TODO: Implement formatCss() method.
}
}
interface IMobileFormat{
public function formatCss();
}
//mobile实现这个接口
class Mobile implements IMobileFormat{
public function formatCss()
{
echo "this is mobile";
}
}
//创建一个Mobile实现这个接口
class MobileAdapter implements IFormat{
private $mobile;
public function __construct(IMobileFormat $mobileNow)
{
$this->mobile = $mobileNow;
}
public function formatCss()
{
$this->mobile->formatCss();
}
}
class Client{
private $mobile;
private $mobileAdapter;
public function __construct()
{
$this->mobile = new Mobile();
$this->mobileAdapter = new MobileAdapter($this->mobile);
$this->mobileAdapter->formatCss();
}
}
$data = new Client();