PHP设计模式之工厂模式与单例模式的示例分析

发布时间:2021-08-31 15:01:35 作者:小新
来源:亿速云 阅读:87

这篇文章将为大家详细讲解有关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设计模式之工厂模式与单例模式的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. JavaScript设计模式之单例模式的示例分析
  2. php设计模式之抽象工厂模式的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:Debian7安装VMware Tools详细过程

下一篇:php中如何发送http请求

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》