1.单例模式
个人理解:一个类只能创建一个实例对象。
好处:减少重复对象的创建,节约内存资源
class Single{
private $instance;
private function __construct(){
}
public static function getInstance(){
if(!self::$instance)
self::$instance = new self();
return self::$instance;
}
private function __clone(){
}
}
2.工厂模式
个人理解:许多类型相似的对象可以通过一个工厂来创建,而不用单独实例每个对象
好处:节约写代码吧
abstract class Operation{
abstract public function getValue($num1,$num2);
}
class OperatorAdd extends Operation{
public function getValue($num1,$num2){
return $num1 + $num2;
}
}
class OperatorSub extends Operation{
public function getValue($num1,$num2){
return $num1 - $num2;
}
}
class OperatorDiv extends Operation{
public function getValue($num1,$num2){
return $num1 / $num2;
}
}
Class Factory{
public static function createObj($operator){
switch($operator){
case "+":
return new OperatorAdd();
break;
case "-":
return new OperatorSub();
break;
case "/":
return new OperatorDiv();
break;
}
}
}
Class Factory{
public static function createObj($operator){
switch($operator){
case "+":
return new OperatorAdd();
break;
case "-":
return new OperatorSub();
break;
case "/":
return new OperatorDiv();
break;
}
}
}
2.1把单例和工厂结合一下
Class FactorySingle{
private static $instance = array();
public static function createObj($operator){
switch($operator){
case "+":
if(!isset(self::$instance['OperatorAdd'])){
self::$instance['OperatorAdd'] = new OperatorAdd();
}
return self::$instance['OperatorAdd'];
break;
case "-":
if(!isset(self::$instance['OperatorSub'])){
self::$instance['OperatorSub'] = new OperatorSub();
}
return self::$instance['OperatorAdd'];
break;
case "/":
if(!isset(self::$instance['OperatorDiv'])){
self::$instance['OperatorDiv'] = new OperatorDiv();
}
return self::$instance['OperatorDiv'];
break;
}
}
}
网友评论