php设计模式总结-工厂模式
使用工厂模式的目的或目标?
工厂模式的最大优点在于创建对象上面,就是把创建对象的过程封装起来,这样随时可以产生一个新的对象。
减少代码进行复制粘帖,耦合关系重,牵一发动其他部分代码。
通俗的说,以前创建一个对象要使用new,现在把这个过程封装起来了。
假设不使用工厂模式:那么很多地方调用类a,代码就会这样子创建一个实例:new a(),假设某天需要把a类的名称修改,意味着很多调用的代码都要修改。
工厂模式的优点就在创建对象上。
工厂模式的优点就在创建对象上。建立一个工厂(一个函数或一个类方法)来制造新的对象,它的任务就是把对象的创建过程都封装起来,
创建对象不是使用new的形式了。而是定义一个方法,用于创建对象实例。
这篇文章主要介绍了php设计模式之工厂模式与单例模式,简单介绍的工厂模式与单例模式的功能,并结合实例形式分析了工厂模式及单例模式的实现与应用,需要的朋友可以参考下,具体如下:
工厂模式:应对需求创建相应的对象
class factory{
function construct($name){
if(file_exists('./'.$name.'.class.php')){
return new $name;
}else{
die('not exist');
}
}
}
单例模式:只创建一个对象的实例,不允许再创建实例,节约资源(例如数据库的连接)
class instance{
public $val = 10;
private static $instance ;
private function construct(){}
private function clone(){}
//设置为静态方法才可被类调用
public static function getinstance(){
/*if(!isset(self::$instance)){
self::$instance = new self;
}*/
if(!isset(instance::$instance)){
instance::$instance = new self;
}
return instance::$instance;
}
}
$obj_one = instance::getinstance();
$obj_one->val = 20;
//clone可以调用clone()克隆即new出一个新的的对象
//$obj_two = clone $obj_one;
$obj_two = instance::getinstance();
echo $obj_two->val;
echo '<p>';
var_dump($obj_one,$obj_two);
运行结果如下:
20
object(instance)[1]
public 'val' => int 20
object(instance)[1]
public 'val' => int 20
应用:数据库连接类(database access oject)
class mysqldb{
private $arr = array(
'port' => 3306,
'host' => 'localhost',
'username' => 'root',
'passward' => 'root',
'dbname' => 'instance',
'charset' => 'utf8'
);
private $link;
static $instance;
private function clone(){}
private function construct(){
$this->link = mysql_connect($this->arr['host'],$this->arr['username'],$this->arr['passward']) or die(mysql_error());
mysql_select_db($this->arr['dbname']) or die('db error');
mysql_set_charset($this->arr['charset']);
}
static public function getinsance(){
if(!isset(mysqldb::$instance)){
mysqldb::$instance = new self;
}
return mysqldb::$instance;
}
public function query($sql){
if($res = mysql_query($sql)){
return $res;
}return false;
}
//fetch one
public function get_one($sql){
$res = $this->query($sql);
if($result = mysql_fetch_row($res)){
return $result[0];
}
}
//fetch row
public function get_row($sql){
$res = $this->query($sql);
if($result = mysql_fetch_assoc($res)){
return $result;
}
return false;
}
//fetch all
public function get_all($sql){
$res = $this->query($sql);
$arr = array();
while($result = mysql_fetch_assoc($res)){
$arr[] = $result;
}
return $arr;
}
}
$mysql = mysqldb::getinsance();
以上就是php 设计模式之工厂模式详解的详细内容。