Home > php教程 > php手册 > PHP最常用的2种设计模式工厂模式和单例模式介绍

PHP最常用的2种设计模式工厂模式和单例模式介绍

WBOY
Release: 2016-06-13 11:58:53
Original
827 people have browsed it

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


用在真正开发中一般当做数据库选择类。
2单例模式
单例是因为一个就足够了,多了浪费。比如邮局里的电话簿只有一本,有需要的人拿来看,没有必要每个人要查的时候工作人员就拿一本出来,看完了再回收。

复制代码 代码如下:


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


实际中用作数据库连接类和工厂模式一起使用,根据参数调用单例模式,可以提高资源使用效率。
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template