The use of PHP advanced objects to build the factory pattern

  • 2020-05-12 02:20:30
  • OfStack

Use of the PHP design pattern factory pattern

 
<?php 
/* 
*  Daily practice  PHP The use of the design pattern factory pattern  
* PHP The factory model is not hard to understand 1 A processing plant, and then a factory that makes products, just makes products  
*  There must be several elements: " methods " . " model " . " The factory workshop " .  
*/ 
/* The first 1 Kind of sample   General factory model  
* */ 
abstract class model {// The product model  
abstract function getNames(); 
} 
class zhangsan extends model {// The product instance  
function getNames(){ 
return "my name is zhengsan"; 
} 
} 
class lisi extends model{// The product instance  
function getNames(){ 
return "my name is lisi"; 
} 
} 
abstract class gongchangModel {// The factory model  
abstract function getZhangsan(); 
abstract function getLisi(); 
} 
class gongchang extends gongchangModel{// Factory instance  
function getZhangsan(){ 
return new zhangsan(); 
} 
function getLisi(){ 
return new lisi(); 
} 
} 
$gongchang=new gongchang();// Example chemical plant  
$zhangsan=$gongchang->getZhangsan();// Manufacturing products  
echo $zhangsan->getNames();// Product output function  
?> 

I wrote about the factory design pattern earlier, in fact, the factory pattern contains both the general factory pattern and the abstract factory pattern, but whatever the factory pattern is, they all have one purpose, which is to generate objects.
Ok, let's use the very simple example below to demonstrate the factory mode in PHP design mode 1.
I have summarized three elements of the factory model:
1. Product model
2. Product example
3. Factory floor
 
<?php 
abstract class prModel {// The product model  
abstract function link(); 
} 
class webLink extends prModel{// The instance 1 A product  
public function link(){ 
echo "www.ofstack.com"; 
} 
} 
class gongchang {// The factory  
static public function createLink (){ 
return new webLink(); 
} 
} 
$weblink=gongchang::createLink();// Made in a factory 1 An object  
$weblink->link();// The output  www.ofstack.com 
?> 

The above method simply shows how to use the factory class. Focus on object orientation


Related articles: