Introduction to the two most commonly used design patterns in PHP, factory pattern and singleton pattern_PHP Tutorial

WBOY
Release: 2016-07-21 15:17:07
Original
842 people have browsed it

1. The main function of factory mode
is to reduce coupling.

Copy code The code is as follows:

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 );

is generally used as a database selection class in real development.
2 Singleton Mode
Singleton is because one is enough, and more is a waste. For example, there is only one phone book in the post office. People who need it can read it. There is no need for the staff to take out one copy when everyone wants to check it, and then recycle it after reading.
Copy code 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( );

In practice, it is used as a database connection class and factory mode. Calling singleton mode according to parameters can improve resource usage efficiency.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325750.htmlTechArticle1. The main function of the factory mode is to reduce coupling. Copy the code The code is as follows: abstract class Operation{ abstract public function getValue($num1,$num2); public function getAttr(){ retu...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!