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.
http://www.bkjia.com/PHPjc/325750.htmlwww.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...