<?php
// 共同接口
interface db
{
function conn();
}
class dbmysql implements db
{
public function conn()
{
echo '连接上了MySQL';
}
}
class dbsqlite implements db
{
public function conn()
{
echo '连接上了sqlite';
}
}
//// 客户端 不知道dbmysql 和 dbsqlite 的内部细节,只知道实现了db接口
//$db = new dbmysql();
//$db->conn();
class Factory
{
public static function createDB($type)
{
if ($type == 'mysql') {
return new dbmysql();
} elseif ($type == 'sqlite') {
return new dbsqlite();
} else {
throw new \Exception('Error db type', 1);
}
}
}
// 客户端 现在不知道服务端到底有那些类
$mysql = Factory::createDB('mysql');
$mysql->conn();
$mysql = Factory::createDB('sqlite');
$mysql->conn();
$mysql = Factory::createDB('oracle');
$mysql->conn();