猿问

在大话PHP设计模式中,这第六章所讲的真的是适配器吗?

 我自己参照网上写了一个Mysql的适配器, 请大神帮看看是不是适配器模式的...


<?php

class MysqlAdapter{   //适配器
   protected $host;
   protected $uname;
   protected $passwd;
   protected $dbname;

   public function __construct($host,$uname, $passwd, $dbname)
   {
       $this->host = $host;        $this->uname=$uname;
       $this->passwd = $passwd;       $this->dbname=$dbname;
   }

   public function Adapt($adaptee){
       return new $adaptee($this->host,$this->uname, $this->passwd, $this->dbname);
   }

}

class MysqliAdaptee {   //适配模块
   protected $link;
   function __construct($host, $username, $password, $databaseName)
   {
       $conn = mysqli_connect($host, $username, $password, $databaseName);
       $this->link = $conn;
       if($this->link) echo "Login success!";
       else echo "Login failed!";

   }
   function query($sql)
   {
       return mysqli_query($this->link, $sql);

   }
   function close()
   {
       mysqli_close($this->link);
   }
}

$MysqlAdapter = new MysqlAdapter("localhost","root","123456","test");  //创建Mysql适配器
$link = $MysqlAdapter->Adapt(MysqliAdaptee::class);   //选择适配模块

$result = $link->query("show databases");
$data = mysqli_fetch_all($result);
var_dump($data);
$link->close();



Darkspirit暗灵
浏览 1265回答 0
0回答
随时随地看视频慕课网APP
我要回答