PHP设计模式之工厂模式与单例模式

本文实例讲述了PHP设计模式之工厂模式与单例模式实现方法分享给大家供大家参考,具体如下:

设计模式简单说应对某类问题而设计的解决方

工厂模式:

rush:PHP;"> class factory{ function __construct($name){ if(file_exists('./'.$name.'.class.PHP')){ return new $name; }else{ die('not exist'); } } }

单例模式:

一个对象的实例,不允许再创建实例,节约资源(例如数据库的连接)

val = 20; //clone可以调用__clone()克隆即new出一个新的的对象 //$obj_two = clone $obj_one; $obj_two = instance::getInstance(); echo $obj_two->val; echo '

'; var_dump($obj_one,$obj_two);

运行结果如下:

int 20 object(instance)[1] public 'val' => int 20

应用:数据库连接类(database access oject)

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相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》、《》及《

希望本文所述对大家PHP程序设计有所帮助。

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...