PHP设计模式 单例模式与工厂模式

//设计模式
//1、单例
//类的计划生育
//1、让该类在外界无法造对象
//2、让外界可以造一个对象,做一个静态方法返回对象
//3、在类里面通过静态变量控制 只有一个

class Cat{
public $name;

private function __construct()
{
}

static $temp;
static function new_ob(){
if(empty(self::$temp)){
self::$temp = new Cat();
}
return self::$temp;
}

function speak(){
return"喵喵喵喵喵";
}
}

$mao = Cat::new_ob();
$mao2 = Cat::new_ob();

$mao->name = "abc";
echo $mao2->name;



//$mao;
//if(empty($mao)){
// $mao = new Cat();
//}
//
//$xxx = $mao;



//工厂模式
//class Jsq
//{
// public $a;
// public $b;
//
// public function jiafa(){
// return $this->a + $this->b;
// }
//}

abstract class Jsq{
public $a;
public $b;
function yunsuan(){

}
}

class Jiafa extends Jsq{
function yunsuan(){
return $this->a + $this->b;
}
}
class Jianfa extends Jsq{
function yunsuan(){
return $this->a - $this->b;
}
}
//$j1 = new jiafa();
//$j1->a = 1;
//$j1->b = 2;
//$j1->yunsuan();

class Factory{
static function creat($x){
switch ($x){
case "+":
return new Jiafa();
break;
case "-": return new Jianfa(); break; } }}$jf = Factory::creat("+");$jf->a = 1;$jf->b = 2;echo $jf->yunsuan();
posted @ 2017-10-17 16:47  奥特曼打不过的小怪兽  阅读(204)  评论(0编辑  收藏  举报