class DomProcessor
{
var $obj_type;
var $obj_name;
private static $instance = null;
function __construct($obj_type)
{
echo 'arrive in __constrct()','<hr/>';
$this->obj_type = $obj_type;
switch($obj_type)
{
case 5:
$this->obj_name = 'Quote';
break;
case 6:
$this->obj_name = 'Contract';
break;
}
}
function getInstance($obj_type)
{
if(!(self::$instance instanceof self ))
{
echo 'have no object','<hr/>';
self::$instance = new DomProcessor($obj_type);
}
else
{
echo 'already have one object','<hr/>';
}
return self::$instance;
}
}
$objType =5;
$processor1 = DomProcessor::getInstance($objType);
echo 'processor1,obj_type:'.$processor1->obj_type.',obj_name:'.$processor1->obj_name.'<hr/>';
$objType = 6;
$processor2 = DomProcessor::getInstance($objType);
echo 'processor2,obj_type:'.$processor2->obj_type.',obj_name:'.$processor2->obj_name.'<hr/>';
$processor3 = DomProcessor::getInstance($objType);
echo 'processor3,obj_type:'.$processor3->obj_type.',obj_name:'.$processor3->obj_name.'<hr/>';
客户端每一次向服务器请求资源,如果引用一个对象中的方法,那么就应该只对该对象实例化一次,所以我就写了以上的代码,会有什么问题吗?
看了输出的结果你就知道了,
have no object
arrive in __constrct()
processor1,obj_type:5,obj_name:Quote
already have one object
processor2,obj_type:5,obj_name:Quote
already have one object
processor3,obj_type:5,obj_name:Quote
这明显只是对obj_type==5时,调用构造函数一次,但是结果应该是obj_type为5时调用一次构造方法,obj_type为6时调用一次构造方法的。
所以对单例模式稍加改造满足我的需求,将语句:if(!(self::$instance instanceof self )) 替换成
if(!(self::$instance instanceof self && self::$instance->obj_type==$obj_type))
就行了,这样就对每一种obj_type只调用一次构造方法了,达到了按照类型来实例化一次类的目的。
改了之后的运行效果:
have no object
arrive in __constrct()
processor1,obj_type:5,obj_name:Quote
have no object
arrive in __constrct()
processor2,obj_type:6,obj_name:Contract
already have one object
processor3,obj_type:6,obj_name:Contract
这样就对了,今天公司的产品马上就要发版了,发现了代码中隐藏的巨大隐患,切记切记,教训很深刻啊。