php-工厂模式

WBOY
Release: 2016-06-23 14:31:21
Original
823 people have browsed it

    针对自己的不足与加深php的认识,选择用php来研究各种设计模式。

    今天就看了设计模式的介绍,并学习了工厂模式,因为工厂模式比较简单,也比较常用。工厂模式的最主要作用就是对象创建的封装、简化创建对象操作。

    下面是一个简单例子:

abstract class Parents
{
 public function show(){}
}

class Sons extends Parents
{
 public function show()
 {
  echo 'i am son!';
 }
}

class Girls extends Parents
{
 public function show()
 {
  echo 'i am girl!';
 }
}

class Factory
{
 private $arrParent = array();
 public function create($parent)
 {
  $this->arrParent[] = new $parent();
 }
 public function show()
 {
  foreach($this->arrParent as $par)
  {
   $par->show();
  }
 }
}

$factory = new Factory();
$factory->create('Sons');
$factory->create('Girls');
$factory->show();
?>

 

工厂模式的应该比较多,用的最多情况就是利用工厂根据条件动态的选择所要创建的对象。这样做的好处是可以在只修改工厂和新增的类就可以添加新的对象创建,对于代码维护和扩展都是个不错的选择,而且动态创建对象的应用带来了更多的灵活性。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template