The two most commonly used design patterns factory patterns and singleton patterns are introduced in PHP

  • 2020-05-19 04:19:15
  • OfStack

1. Factory mode
The main effect is to reduce the coupling.
 
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); 

Used in real development 1 as a database selection class.
2 singleton pattern
The singleton is because one is enough, so much waste. For example, there is only one phone book in the post office. People who need it should take it to see it. It is not necessary for everyone to check it.
 
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 database connection class and factory mode 1, and the singleton mode can be invoked according to the parameters to improve the efficiency of resource use.

Related articles: