1.工厂模式
主要作用是降低耦合度。
复制代码 代码如下:
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);
复制代码 代码如下:
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();