Common php design modes: Factory mode and Singleton mode
- /**
- Example of Factory mode
- @ 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 );
- ?>
-
In actual development, it is generally used as a database selection class. Let's look at the Singleton mode of php design mode: Singleton is unique. Simply put, an object is only responsible for a specific task. for example, there is only one phone book in the post office, which can be viewed by people who need it, there is no need for the staff to take out one copy when they want to check it.
- 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 ();
- ?>
-
Note: The Singleton mode is generally used as a database connection class and often used together with the factory mode. The Singleton mode can be called based on parameters to improve resource usage efficiency. |