Examples of the design pattern factory pattern and singleton pattern in PHP, friends in need can refer to it.
1. Factory mode
Factory pattern is a class that has certain methods that create objects for you. You can use a factory class to create objects without using new directly. This way, if you want to change the type of object created, you only need to change the factory. All code using this factory is automatically changed.
The main function is to reduce coupling.
The code is as follows |
Copy code |
代码如下 |
复制代码 |
abstract class Operation{
abstract public function getValue($num1,$num2);
public function getAttr(){
return 1;
}
}
class Add extends Operation{
public function getValue($num1, $num2){
return $num1+$num2;
}
}
class Sub extends Operation{
public function getValue($num1, $num2){
return $num1-$num2;
}
}
class Factory{
public static function CreateObj($operation){
switch ($operation){
case '+': return new Add();
case '-': return new Sub();
}
}
}
$Op=Factory::CreateObj('-');
echo $Op->getValue(3, 6);
|
abstract class Operation{
abstract public function getValue($num1,$num2);
Public function getAttr(){
Return 1;
}
}
代码如下 |
复制代码 |
interface IUser
{
function getName();
}
class User implements IUser
{
public static function Load( $id )
{
return new User( $id );
}
public static function Create( )
{
return new User( null );
}
public function __construct( $id ) { }
public function getName()
{
return "Jack";
}
}
$uo = User::Load( 1 );
echo( $uo->getName()."n" );
?>
|
class Add extends Operation{
Public function getValue($num1, $num2){
return $num1+$num2;
}
}
class Sub extends Operation{
Public function getValue($num1, $num2){
return $num1-$num2;
}
}
class Factory{
Public static function CreateObj($operation){
switch ($operation){
case '+': return new Add();
case '-': return new Sub();
}
}
}
$Op=Factory::CreateObj('-');
echo $Op->getValue(3, 6);
|
Used in real development, it is generally used as a database selection class.
Example 2 shows an example of using factory methods.
The code is as follows |
Copy code |
interface IUser<🎜>
{<🎜>
function getName();<🎜>
}<🎜>
<🎜>class User implements IUser<🎜>
{<🎜>
public static function Load( $id ) <🎜>
{<🎜>
return new User( $id );<🎜>
}<🎜>
<🎜> public static function Create( ) <🎜>
{<🎜>
return new User( null );<🎜>
}<🎜>
<🎜> public function __construct( $id ) { }<🎜>
<🎜> public function getName()<🎜>
{<🎜>
Return "Jack";<🎜>
}<🎜>
}<🎜>
<🎜>$uo = User::Load( 1 );<🎜>
echo( $uo->getName()."n" );
?>
|
This code is much simpler. It has only one interface IUser and a User class that implements this interface. The User class has two static methods for creating objects. This relationship can be represented by UML in Figure 2
Improving efficiency through factory mode in PHP
We create the following four files
The code is as follows |
Copy code |
代码如下 |
复制代码 |
index.php
include_once("f.inc.php");
$f=new factory;
$t1=&$f->create('T1');
echo $t1->getName();
echo $config;
?>
f.inc.php
class factory
{
function factory()
{
$this->mClasses=array('T1'=>'t1.inc.php','T2'=>'t2.inc.php');
}
function &create($class)
{
if (!class_exists($class))
{
require_once($this->mClasses[$class]);
}
return new $class;
}
}
?>
t1.inc.php
global $config;
$config='surfchen';
class T1
{
var $mName='name::T1';
function getName()
{
return $this->mName;
}
}
?>
t2.inc.php
class T2
{
function T2()
{
echo 't2 is ok';
}
}
?>
|
index.php
include_once("f.inc.php");
$f=new factory;
$t1=&$f->create('T1');
echo $t1->getName();
echo $config;
?>
代码如下 |
复制代码 |
global $config;
$config='surfchen'; |
f.inc.php
class factory<🎜>
{<🎜>
function factory()<🎜>
{<🎜>
$this->mClasses=array('T1'=>'t1.inc.php','T2'=>'t2.inc.php');
}
function &create($class)
{
if (!class_exists($class))
{
require_once($this->mClasses[$class]);
}
Return new $class;
}
}
?>
t1.inc.php
global $config;<🎜>
$config='surfchen';<🎜>
class T1<🎜>
{<🎜>
var $mName='name::T1';<🎜>
function getName()<🎜>
{<🎜>
Return $this->mName;
}
}
?>
t2.inc.php
class T2<🎜>
{<🎜>
function T2()<🎜>
{<🎜>
echo 't2 is ok';<🎜>
}<🎜>
}<🎜>
?>
|
In index.php, we create other class instances through a factory class.
In the factory, there is an array $this->mClasses saved in the format of array("class name" => "class file path").
When we create a class instance through factory::create(), in create(), it will first detect whether the class exists. If it does not exist, the class file corresponding to the class will be included according to $this->mClasses. Then create and return an instance of this class.
In this way, we only need to include the factory class file into the executed script (such as index.php).
You may also notice these two lines of code in t1.inc.php.
The code is as follows |
Copy code |
global $config;
$config='surfchen'; |
2 Singleton Mode
To put it simply, the PHP singleton mode is a function implemented by a class, and only one instance of this class exists in the entire application;
The factory pattern emphasizes object-oriented polymorphism. It can encapsulate functional differences and implement common functions externally, such as database links. Due to different databases, we may need to write different methods. To realize the database link, but as an application, it does not need to know whether the database uses MySQL or Oracle. It only needs to use the query() method to perform the corresponding operations of the database. This masks the differences and makes the class more robust!
The code is as follows
代码如下 |
复制代码 |
class Mysql{
public static $conn;
public static function getInstance(){
if (!self::$conn){
new self();
return self::$conn;
}else {
return self::$conn;
}
}
private function __construct(){
self::$conn= "mysql_connect:";// mysql_connect('','','')
}
public function __clone()
{
trigger_error("Only one connection");
}
}
echo Mysql::getInstance();
echo Mysql::getInstance();
|
|
Copy code
|
| class Mysql{
Public static $conn;
Public static function getInstance(){
if (!self::$conn){
new self();
return self::$conn;
}else {
return self::$conn;
}
}
Private function __construct(){
self::$conn= "mysql_connect:";// mysql_connect('','','')
}
Public function __clone()
{
trigger_error("Only one connection");
}
}
echo Mysql::getInstance();
echo Mysql::getInstance();
In practice, it is used as a database connection class and factory mode. Calling singleton mode according to parameters can improve resource usage efficiency
http://www.bkjia.com/PHPjc/631278.htmlwww.bkjia.com
trueTechArticleExamples of design pattern factory pattern and singleton pattern in php, friends in need can refer to it. 1. Factory Pattern Factory Pattern is a class that has certain methods that create objects for you. You can...