How to use PHP design pattern Factory mode
Copy Code code as follows:
<?php
/*
* Daily practice of PHP design mode Factory mode use method
* PHP Factory model is not difficult to understand, as the name suggests, is a processing plant, and then the factory is manufactured products, as long as the manufacture of products
* There must be several elements: "Method", "model", "Factory workshop".
*/
/* First example Common Factory mode
* */
Abstract class Model {//Product models
Abstract function getNames ();
}
Class Zhangsan extends Model {//Product instance
function GetNames () {
Return ' My name is Zhengsan ';
}
}
Class Lisi extends model{//product instance
function GetNames () {
Return ' My name is Lisi ';
}
}
Abstract class Gongchangmodel {//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 ()//instance chemical plant
$zhangsan = $gongchang->getzhangsan ()//Manufacturing Products
echo $zhangsan->getnames ()//Product output function
?>
Before I wrote about the factory design patterns, in fact, the factory model contains common factory patterns and abstract factory patterns, but, regardless of the factory model, they all have a role, that is to generate objects.
Well, let's use the simplest example below to demonstrate the factory pattern in the PHP design pattern again.
I have summed up the three elements of the factory model:
First, the product model
Second, the product example
Third, the factory workshop
Copy Code code as follows:
<?php
Abstract class Prmodel {//product model
Abstract function link ();
}
Class Weblink extends prmodel{//instance a product
Public Function link () {
echo "Www.jb51.net";
}
}
Class Gongchang {//Factory
static public Function Createlink () {
return new Weblink ();
}
}
$weblink =gongchang::createlink ()//Make an object through the factory
$weblink->link ();//Output www.jb51.net
?>
The above method, it is simple to explain the use of the factory class method. Focus on Object oriented