Explanation of "simple factory mode" instance code in PHP

Source: Internet
Author: User
Simple factory mode instance code in PHP. for php-like learning, refer to the simple factory mode below:
① 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

After reading the article, let's look back at this figure. The effect will be better.



Encapsulation

The code is as follows:


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, to add a "remainder" operation, you must add a branch statement in the switch statement block. the code must be modified as follows:
Add branch statement

The code is as follows:


Class Calc {
Public function calculate ($ num1, $ num2, $ operator ){
Try {
$ Result = 0;
Switch ($ operator ){
// ...... Omitted ......
Case '% ':
$ Result = $ num1 % $ num2;
Break;
// ...... Omitted ......
}
} Catch (Exception $ e ){
Echo "Your input is incorrect:". $ e-> getMessage ();
}
}
}
?>


Code Analysis: Using the above method to add new function operations to the calculator has the following disadvantages:
① 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's execution efficiency has to be greatly reduced by involving other irrelevant interpretations.
Solution: adopting the inheritance and polymorphism of OOP
Preliminary Implementation of the simple factory model

The code is as follows:


/**
* 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.

The code is as follows:


/**
* Retrieve the remainder class (remainder)
*
*/
Class OperationRem extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 % $ num12;
}
}
?>


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 the factory
The code is as follows:

The code is as follows:


/**
* 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;
?>


Original article, reproduced please indicate the source: http://www.cnblogs.com/hongfei/

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.