2.5. 适配器模式(Adapter)

未匹配的标注

uml

PHP

实现类

  1. 他们需要实现什么接口? SqlAdapterInterface
  2. 实现接口的具体类 SqlServer Mysql
  3. 适配器调用类 SqlAdapter

代码实现

<?php

//数据库适配器   必须实现这些接口
interface SqlAdapterInterface
{
    // 连接
    public function connection();
}

class Mysql implements SqlAdapterInterface
{
    public function connection()
    {
        echo 'mysql连接成功'.PHP_EOL;
    }
}

class SqlServer implements SqlAdapterInterface
{

    public function connection()
    {
        echo 'sqlServer连接成功'.PHP_EOL;
    }
}


//执行者
class SqlAdapter
{
    protected $server;
    public function __construct(SqlAdapterInterface $server)
    {
        $this->server = $server;
    }

    public function init()
    {
        $this->server->connection();
    }
}


$mysqlAdapter = (new SqlAdapter(
    new Mysql()
));

$sqlServerAdapter = (new SqlAdapter(
    new SqlServer()
));
$mysqlAdapter->init();
$sqlServerAdapter->init();

场景

我知道 mysql 可以用 init() 创建连接,

我想用 sqlserver了,请问 sqlserver 要怎么创建连接啊?

哦,还是 init() 啊。

(后续这个类可能会变复杂,有delete update等等命令)

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~