php設計模式
設計模式
單例模式
1.將構造函數變成私有的
2.提供一個靜態方法來返回對象
3.在方法裏面加限制條件
class Ren{
public $name;
public static $dx;
private function __construct(){
}
public static function duixiang(){
if(empty(Ren::$dx)){
Ren::$dx = new Ren();
}
return Ren::$dx;
}
}
$r = Ren::duixiang();
$r->name = "張三";
$r1 = Ren::duixiang();
var_dump($r1);
//工廠模式
/*class YunSuan{
public $a;
public $b;
public function jia(){
return $this->a+$this->b;
}
public function jian(){
return $this->a-$this->b;
}
public function cheng(){
return $this->a*$this->b;
}
public function chu(){
return $this->a/$this->b;
}
}*/
//做為父類
/*class YunSuan{
public $a;
public $b;
public function suan(){
}
}
class Jia extends YunSuan{
public function suan(){
return $this->a+$this->b;
}
}
class Jian extends YunSuan{
public function suan(){
return $this->a-$this->b;
}
}
class Yu extends YunSuan{
public function suan(){
return $this->a%$this->b;
}
}
//工廠類
class GongChang{
public static function duixiang($ysf){
switch($ysf){
case "+":
return new Jia();
break;
case "-":
return new Jian();
break;
case "%":
return new Yu();
break;
}
}
}
$y = GongChang::duixiang("-");
$y->a = 10;
$y->b = 5;
echo $y->suan();*/
php設計模式