1. Factory Model
The main function is to reduce coupling.
Copy codeThe Code is as follows: 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 );
Generally used in real development as a database selection class.
2 Singleton Mode
For example, one is enough, which is a waste. For example, there is only one phone book in the post office. If there is a need for someone to look at it, there is no need for everyone to check it out and retrieve it after reading it.Copy codeThe Code is as follows: 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 ();
In practice, it is used together as a database connection class and a factory mode. Calling the singleton mode based on parameters can improve resource usage efficiency.