-
- /**
- Example of factory pattern
- @link http://bbs.it-home.org
- */
- abstract class Operation{
- abstract public function getValue($num1,$num2);
- public function getAttr(){
- return 1;
- }
- }
- class Add extends Operation{
- public function getValue($num1, $num2){
- return $num1+$num2;
- }
- }
- class Sub extends Operation{
- public function getValue($num1, $num2){
- return $num1-$num2;
- }
- }
- class Factory{
- public static function CreateObj($operation){
- switch ($operation){
- case '+': return new Add();
- case '-': return new Sub();
- }
- }
- }
- $Op=Factory::CreateObj('-');
- echo $Op->getValue(3, 6);
- ?>
-
Copy code
In actual development, it is generally used as a database selection class.
Let’s look at the singleton mode of PHP design pattern: a singleton is the only one that exists. Simply put, an object is only responsible for a specific task;
For example, there is only one phone book in the post office. People who need it can read it. There is no need for the staff to take out one copy when everyone wants to check it, and then recycle it after reading.
-
- class Mysql{
- public static $conn;
- public static function getInstance(){
- if (!self::$conn){
- new self();
- return self:: $conn;
- }else {
- return self::$conn;
- }
- }
- private function __construct(){
- self::$conn= "mysql_connect:";// mysql_connect('','','' )
- }
- public function __clone()
- {
- trigger_error("Only one connection");
- }
- }
- echo Mysql::getInstance();
- echo Mysql::getInstance();
- ?>
-
Copy code
Instructions:
The singleton mode is mostly used as a database connection class and is often used together with the factory mode. Calling the singleton mode according to parameters can improve resource usage efficiency.
|