1. Single-case mode
1<?PHP2 class Mysql{3 Private Static $instance=NULL;4 Private $conn;5 //construction method, set to private, does not allow the object to be obtained through new6 Private function__construct () {7 $conn=mysql_connect("localhost", "root", "" ");8 }9 Public Static functiongetinstance () {Ten if(!self::$instanceinstanceof Self) { OneSelf::$instance=NewSelf ; A } - returnSelf::$instance; - } the //prevent users from replicating object instances - Private function__clone () {} - } - $db=Mysql::getinstance (); +?>
2. Factory mode
1<?PHP2 //define an abstract class that allows subclasses to inherit and implement it.3 Abstract classoperation{4 Abstract Public functionGetValue ($num 1,$num 2);//subclasses must implement this method5 }6 7 //Addition Class8 classOperationaddextendsoperation{9 Public functionGetValue ($num 1,$num 2){Ten return $num 1+$num 2; One } A } - //Subtraction Class - classOperationsubextendsoperation{ the Public functionGetValue ($num 1,$num 2){ - return $num 1-$num 2; - } - } + //Multiplication Class - classOperationmulextendsoperation{ + Public functionGetValue ($num 1,$num 2){ A return $num 1*$num 2; at } - } - //Division class - classOperationdivextendsoperation{ - Public functionGetValue ($num 1,$num 2){ - Try{ in if($num 2= = 0){ - Throw New Exception("Divisor cannot be 0"); to}Else{ + return $num 1/$num 2; - } the}Catch(Exception $e){ * Echo"Error message:".$e-getMessage (); $ }Panax Notoginseng } - } the /** + * Factory class, used primarily to create objects A * Function: According to the input operation symbol, the factory can instantiate the suitable object the */ + classfactory{ - Public Static functionCreateobj ($operate){ $ Switch($operate){ $ Case' + ': - return NewOperationadd (); - Break; the Case‘-‘: - return Newoperationsub ();Wuyi Break; the Case‘*‘: - return NewOperationmul (); Wu Break; - Case‘/‘: About return NewOperationdiv (); $ Break; - } - } - } A $test=factory::createobj ('/'); + $result=$test->getvalue (23,0); the Echo $result; -?>
PHP design mode