S1:适配器 Adapter

将一个类的接口转换为用户期望的另外一个接口.适配器使得原本由于接口不兼容而不能一起工作的类可以一起工作  

UML:

 

一.类适配器:

class A
{
   public function methodA()
   {
    ..............
   }
}
 
class Adapter extends A
{
   private $objectA;
    
   public function methodB()
   {
    echo 'Append data';
   }
}
 
调用:
 
$a = new Adapter();
$a->methodA();
$a->methodB();

  

二.对象适配器:

const HOST = '127.0.0.1';
const USER = 'root';
const PASSWORD = 'root';
const DB_NAME = 'test';

interface Db
{
    public function connect();
    public function select($sql);
}

class MysqlDb implements Db
{
    protected  $conn;

    public function connect()
    {
        $this->conn = mysql_connect(HOST, USER, PASSWORD);
        mysql_select_db(DB_NAME, $this->conn);
    }

    public function select($sql)
    {
        $res = mysql_query($sql, $this->conn);
        $data = array();
        while ($row = mysql_fetch_assoc($res)) {
            $data[] = $row;
        }
        return $data;
    }
}

class MysqliDb implements Db
{
    protected  $conn;

    public function connect()
    {
        $this->conn = mysqli_connect(HOST, USER, PASSWORD);
        mysqli_select_db($this->conn, DB_NAME);
    }

    public function select($sql)
    {
        $res = mysqli_query($this->conn, $sql);
        $data = array();
        while ($row = mysqli_fetch_assoc($res)) {
            $data[] = $row;
        }
        return $data;
    }
}

class DbAdapter
{
    const MYSQL = 'MysqlDb';
    const MYSQLI = 'MysqliDb';
    protected  $db;

    public function __construct($type)
    {
        $this->db = new $type();
    }

    public function connectDb()
    {
        $this->db->connect();
    }

    public function select($sql)
    {
        return $this->db->select($sql);
    }
}

$db = new DbAdapter(DbAdapter::MYSQLI);
$db->connectDb();
var_dump($db->select("select * from test"));

  

三.接口适配器

要求现有类ExistClass适配接口DemoInterface

现有类:

class ExistClass
{
}

interface DemoInterface
{
    public function method();
}

// 适配的新类
class NewClass extends ExistClass implements DemoInterface
{
    public function method()
    {
        // TODO: Implement method() method.
    }

}

  

posted @ 2017-11-05 15:36  rorshach  阅读(215)  评论(0编辑  收藏  举报