基础工厂类与图像解析示例
基础工厂类的结构示例
具体实现代码如下所示:
class MyObject{
//该对象将由工厂方法返回
}
class MyFactory{
public static function factory(){
return new MyObject();
}
}
$instance=MyFactory::factory();利用工厂类处理图像文件解析
相关代码实现如下:
<?phpinterface IImage{
function getHeight();
function getWidth();
function getData();
}
class Image_PNG implements IImage{
private $_width,$_height,$_data;
public function __construct($file){
$this->_file=$file;
$this->_parse();
}
private function _parse(){
//执行PNG格式数据的解析逻辑
//同时填充成员变量$_width,$_height,$_data;
}
public function getWidth(){
return $this->_width;
}
public function getHeight(){
return $this->_height;
}
public function getData(){
return $this->_data;
}
}
class Image_JPEG implements IImage{
private $_width,$_height,$_data;
public function __construct($file){
$this->_file=$file;
$this->_parse();
}
private function _parse(){
//执行JPEG格式数据的解析逻辑
//同时填充成员变量$_width,$_height,$_data;
}
public function getWidth(){
return $this->_width;
}
public function getHeight(){
return $this->_height;
}
public function getData(){
return $this->_data;
}
}
class ImageFactory{
public static function factory($file){
$pathParts=pathinfo($file);
switch (strtolower($pathParts['extension']))
{
case 'jpg':
$ret=new Image_JPEG($file);
break;
case 'png':
$ret=new Image_PNG($file);
break;
default:
//出现错误情况
}
if($ret instanceof IImage){
return $ret;
}else {
//出现错误情况
}
}
}
//当调用工厂方法传入图像文件名时,系统依据文件类型生成对应的对象实例。
//调用ImageFactory
$image=ImageFactory::factory('/path/to/my.jpg');
//此时$image为Image_JPEG类的实例
echo $image->getWidth();应用工厂模式解决数据库移植性问题
在开发数据库应用程序时,工厂模式主要在以下两个维度发挥作用。
.增强软件对不同数据库平台的支持能力,有助于扩大用户群体
.对于内部使用的软件,若需更换数据库,可轻松将应用迁移至其他平台
代码中构建了一个名为User的数据库表进行测试,该表包含一个varchar类型的email字段
具体代码实现如下:
<?phpinterface IDatabaseBindings{
public function userExists($email);
}
class PGSQL implements IDatabaseBindings{
protected $_connection;
public function __construct(){
$this->_connection=pg_connect('dbname=example_db');
}
public function userExists($email){
$emailEscaped=pg_escape_string($email);
$query="select 1 from users where email='".$emailEscaped."'";
if($result=pg_query($query,$this->_connection)){
return (pg_num_rows($result)>0)?true:false;
}else{
return false;
}
}
}
class MYSQL implements IDatabaseBindings{
protected $_connection;
public function __construct(){
$this->_connection=mysql_connect('localhost');
mysql_select_db('example_db',$this->_connection);
}
public function userExists($email){
$emailEscaped=mysql_real_escape_string($email);
$query="select 1 from users where email='".$emailEscaped."'";
if($result=mysql_query($query,$this->_connection)){
return (mysql_num_rows($result)>0)?true:false;
}else{
return false;
}
}
}
class DatabaseFactory{
public static function factory(){
$type=loadtypefromconfigfile();
switch ($type){
case 'PGSQL':
return new PGSQL();
break;
case 'MYSQL':
return new MYSQL();
break;
}
}
}应用程序无需知晓具体连接的数据库类型,仅需依据IDatabaseBindings接口定义的规范,直接与工厂返回的实例进行交互。
//调用DatabaseFactory
$db=DatabaseFactory::factory();
$db->userExists('person@example.com');