PHP中的实现AbstractFactory模式

来源:互联网 发布:看图纸dwg for mac 编辑:程序博客网 时间:2024/05/02 02:05

<?php
/**
 * 数据库连接抽象工厂
 * filename: IAbstractFactory.php
 
*/
interface IAbstractFactory{
    
function getMysqlConnection();
    
function getOracleConnection();
}
?>

<?php
/**
 * filename: ConnectionFactory.php
 
*/
require_once 'IAbstractFactory.php';
require_once 'MysqlConnection.php';
require_once 'OracleConnection.php';
/**
 * 数据库连接工厂
 
*/
class ConnectionFactory implements IAbstractFactory {
    
/**
     * uri scheme 一个uri的模式部分,例如 JDBC数据库连接 jdbc:mysql://localhost:3306/test
     * 这里的scheme部分为jdbc,还有其他的比如 http,ftp,https 等等 
     * @access private
     
*/
    
protected $scheme = null;
    
public function getMysqlConnection() {
        
return new MysqlConnection();
    }
    
public function getOracleConnection() {
        
return new OracleConnection();
    }
}
?>

 

<?php
/**
 * 数据库连接接口
 * filename: IConnection.php
 
*/
interface IConnection {
}
?>

 

数据库链接实现

 

<?php
/**
 * filename: MysqlConnection.php
 
*/
require_once 'IConnection.php';
class MysqlConnection implements IConnection {
    
function __construct() {
    }
}
?>
<?php
/**
 * filename: OracleConnection.php
 
*/
require_once 'IConnection.php';
class OracleConnection implements IConnection {
    
function __construct() {
    }
}
?>

UnitTestCase

<?php
require_once 'simpletest/unit_tester.php';
require_once 'simpletest/reporter.php';
require_once 'ConnectionFactory.php';
require_once 'MysqlConnection.php';
/**
 * Database Factory Test Case 
 * 
 
*/
class FactoryTestCase extends UnitTestCase {
    
function testFactoryAndConnection() {
        
// factory test
        $factory = new ConnectionFactory();
        
$this->assertNotNull($factory);
        
$this->assertIsA($factory, 'ConnectionFactory');
        
// mysql connection test
        $connection = $factory->getMysqlConnection();
        
$this->assertNotNull($connection);
        
$this->assertIsA($connection, 'MysqlConnection');
        
// oracle connection test
        $connection = $factory->getOracleConnection();
        
$this->assertNotNull($connection);
        
$this->assertIsA($connection, 'OracleConnection');
    }
}
// start test
$test = new FactoryTestCase();
$test->run(new HtmlReporter());
?>
原创粉丝点击