Two most common design modes of PHP: factory mode and Singleton Mode

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.