设计模式
一.单例模式
目的:一个类只能够实例化一个对象
class Ren
{
private static $dx; //用来存储生成的对象
public $name;
//私有的构造函数在外界访问不到
private function __construct()
{
}
//生成对象的方法,用来间接访问,运用静态方法才能访问
public static function DuiXiang()
{
if(empty(self::$dx))
{
self::$dx = new Ren();
}
return self::$dx;
}
}
$r=Ren::DuiXiang();
$r->name="张三";
$r1=REn::DuiXiang();
var_dump($r);
二.工厂模式
/*class suan
{
public $a;
public $b;
function jia()
{
return $this->a + $this->b;
}
function jian()
{
return $this->a - $this->b;
}
}*/ //此方法不安全
class YunSuan
{
public $a;
public $b;
function Suan()
{
}
}
class jia extends YunSuan
{
function Suan()
{
return $this->a + $this->b;
}
}
class jian extends YunSuan
{
function Suan()
{
return $this->a - $this->b;
}
}
class cheng extends YunSuan
{
function Suan()
{
return $this->a * $this->b;
}
}
class chu extends YunSuan
{
function Suan()
{
return $this->a / $this->b;
}
}
//工厂类
class GongChang
{
static function ShengChan($f)
{
switch($f)
{
case "+":
return new jia();
break;
case "-":
return new jian();
break;
case "*":
return new cheng();
break;
case "/":
return new chu();
break;
}
}
}
$r=GongChang::ShengChan("*");
$r->a=10;
$r->b=5;
echo $r->Suan();