Php object-oriented factory mode example-PHP source code

Source: Internet
Author: User
Tags switch case
What is the factory model? Is it in the factory? I believe that some of my friends still have some incomprehension about the php factory model. The following describes some factory model examples. What is the factory model? Is it in the factory? I believe that some of my friends still have some incomprehension about the php factory model. The following describes some factory model examples.

Script ec (2); script

Simple factory mode:


① Abstract base class: Class Defines abstract methods for implementation in sub-classes
② Inherit from the subclass of the abstract base class: implement the abstract methods in the base class
③ Factory class: Used to instantiate objects


First look at a code:

Class Calc {
/**
* Calculation Result
*
* @ Param int | float $ num1
* @ Param int | float $ num2
* @ Param string $ operator
* @ Return int | float
*/
Public function calculate ($ num1, $ num2, $ operator ){
Try {
$ Result = 0;
Switch ($ operator ){
Case '+ ':
$ Result = $ num1 + $ num2;
Break;
Case '-':
$ Result = $ num1-$ num2;
Break;
Case '*':
$ Result = $ num1 * $ num2;
Break;
Case '/':
If ($ num2 = 0 ){
Throw new Exception ("the divisor cannot be 0 ");
}
$ Result = $ num1/$ num2;
Break;
}
Return $ result;
} Catch (Exception $ e ){
Echo "your input is incorrect:". $ e-> getMessage ();
}
}
}
$ Test = new Calc ();
// Echo $ test-> calculate (2, 3, '+'); // print: 5
Echo $ test-> calculate (5, 0, '/'); // print: the input is incorrect. The divisor cannot be 0.
?>

Advantage: the above Code uses the object-oriented encapsulation feature. Other pages can be used as long as the include class is available.

Disadvantages: flexible scalability and Maintenance
For example, if you want to add a "remainder" operation, you must add a branch statement to the switch statement block, and add a case to the Code for judgment.

The following problems occur:

① When you need to change the original code block to "Add new functions", you may accidentally change the original code to an error.
② If you want to add many functions, such as 'multiplication fan', 'open fan', 'login', 'trigonometric function ', and 'statistics', or add some computing functions dedicated to programmers, for example, And, Or, Not, Xor, you need to add N branch statements in the switch statement. Imagine that if a computing function has 20 or 30 case Branch statements, the code will be larger than one screen, which not only greatly reduces the readability of the code, but also the key is to add a small function, the program execution efficiency has to be greatly reduced by involving other irrelevant interpretations.

Solution: adopting the inheritance and Polymorphism of OOP

/**
* Operation class
* Because there are abstract methods, the class must be declared as an abstract class.
*/
Abstract class Operation {
// The abstract method cannot contain the function body.
Abstract public function getValue ($ num1, $ num2); // The subclass must implement this function.
}
/**
* Addition class
*/
Class OperationAdd extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 + $ num2;
}
}
/**
* Subtraction class
*/
Class OperationSub extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1-$ num2;
}
}
/**
* Multiplication
*/
Class OperationMul extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 * $ num2;
}
}
/**
* Division class
*/
Class OperationDiv extends Operation {
Public function getValue ($ num1, $ num2 ){
Try {
If ($ num2 = 0 ){
Throw new Exception ("the divisor cannot be 0 ");
} Else {
Return $ num1/$ num2;
}
} Catch (Exception $ e ){
Echo "error message:". $ e-> getMessage ();
}
}
}
?>

/**
* Operation class
* Because there are abstract methods, the class must be declared as an abstract class.
*/
Abstract class Operation {
// The abstract method cannot contain the function body.
Abstract public function getValue ($ num1, $ num2); // The subclass must implement this function.
}
/**
* Addition class
*/
Class OperationAdd extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 + $ num2;
}
}
/**
* Subtraction class
*/
Class OperationSub extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1-$ num2;
}
}
/**
* Multiplication
*/
Class OperationMul extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 * $ num2;
}
}
/**
* Division class
*/
Class OperationDiv extends Operation {
Public function getValue ($ num1, $ num2 ){
Try {
If ($ num2 = 0 ){
Throw new Exception ("the divisor cannot be 0 ");
} Else {
Return $ num1/$ num2;
}
} Catch (Exception $ e ){
Echo "error message:". $ e-> getMessage ();
}
}
}
?>

Here we use the Object-oriented Inheritance feature. First, we declare a virtual base class and specify the method (getValue () that must be implemented by the subclass in the base class ())

Analysis: By using the Object-oriented Inheritance feature, we can easily expand the original program, for example, 'multiplication fan', 'open fan', 'login', and 'trigonometric function ', 'statistics' and so on.

We only need to write another class (this class inherits the virtual base class) to complete the corresponding functions in the class (for example, evaluate the multiplication operator), and greatly reduce the coupling degree, convenience for future maintenance and expansion.

There is another unsolved problem: how can the program instantiate the corresponding object based on the operator entered by the user?
Solution: Use a separate class to implement the instantiation process. This class is a factory.

/**
* Engineering, mainly used to create objects
* Function: the factory can create an appropriate object based on the input operator number.
*
*/
Class Factory {
Public static function createObj ($ operate ){
Switch ($ operate ){
Case '+ ':
Return new OperationAdd ();
Break;
Case '-':
Return new OperationSub ();
Break;
Case '*':
Return new OperationSub ();
Break;
Case '/':
Return new OperationDiv ();
Break;
}
}
}
$ Test = Factory: createObj ('/');
$ Result = $ test-> getValue (23, 0 );
Echo $ result;
?>

In my summary, different factories (classes) are called based on different passed parameters (objects ). Then it is used to implement the specified function. The major advantage is that it simplifies the switch case, if else, and so on in the previous functional programming to distribute classes. Different things call different classes.

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.