The "Simple Factory mode" instance code in PHP explains _php tutorial

Source: Internet
Author: User
Simple Factory mode:
① abstract base class: Some methods of defining abstractions in classes to implement in subclasses
② inherits from the subclass of the abstract base class: Implementing an abstract method in a base class
③ Factory class: Used to instantiate objects

Read the article and then look back to see this picture, the effect will be better



Package Type
Copy CodeThe code is as follows:
Class calc{
/**
* Calculation results
*
* @param int|float $num 1
* @param int|float $num 2
* @param string $operator
* @return Int|float
*/
Public function Calculate ($num 1, $num 2, $operator) {
try {
$result = 0;
Switch ($operator) {
Case ' + ':
$result = $num 1+ $num 2;
Break
Case '-':
$result = $num 1-$num 2;
Break
Case ' * ':
$result = $num 1* $num 2;
Break
Case '/':
if ($num 2==0) {
throw new Exception ("divisor cannot be 0");
}
$result = $num 1/$num 2;
Break
return $result;
}
}catch (Exception $e) {
echo "You entered in error:". $e->getmessage ();
}
}
}
$test =new Calc ();
echo $test->calculate (2,3, ' + ');//Print: 5
echo $test->calculate (5,0, '/');//Print: You entered the wrong: divisor cannot be 0
?>

Advantage: The above code uses the object-oriented encapsulation feature, as long as the Include this class, other pages can be used casually
Cons: Inability to scale and maintain flexibly
For example, if you want to add a "redundancy" operation, you need to include a branch statement in the switch statement block, the code needs to make the following changes
To add a branch statement
Copy CodeThe code is as follows:
Class calc{
Public function Calculate ($num 1, $num 2, $operator) {
try {
$result = 0;
Switch ($operator) {
//...... Omitted......
Case '% ':
$result = $num 1% $num 2;
Break
//...... Omitted......
}
}catch (Exception $e) {
echo "You entered in error:". $e->getmessage ();
}
}
}
?>

Code Analysis: Using the above method to add a new function to the calculator has the following disadvantages
① need to change the original code block, may be in order to "add new features" and change the original code, accidentally changed the original code is wrong
② If you want to add a lot of features, such as: ' Power ', ' root ', ' log ', ' trigonometric ', ' statistics ', or add some programmer-specific computing functions, such as: and, or, not, Xor, so you need to add N branch statements in the switch statement. Imagine that a function of computing function if there are twenty or thirty case branch statements, the code will be more than one screen, not only make the code readability greatly reduced, the key is, in order to add small functions, but also to let the rest of the irrelevant are involved in interpretation, which makes the execution of the program significantly less efficient
Solution approach: Using OOP's inheritance and polymorphic thinking
Preliminary implementation of simple factory model
Copy CodeThe code is as follows:
/**
* Operation class
* Because an abstract method is included, the class must be declared as an abstract class
*/
Abstract class operation{
Abstract methods cannot contain function bodies
Abstract public Function GetValue ($num 1, $num 2);//strongly require subclasses to implement the function function
}
/**
* Addition class
*/
Class Operationadd extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1+ $num 2;
}
}
/**
* Subtraction Class
*/
Class Operationsub extends Operation {
Public Function GetValue ($num 1, $num 2) {
Return $num 1-$num 2;
}
}
/**
* Multiplication Class
*/
Class Operationmul extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1* $num 2;
}
}
/**
* Division Class
*/
Class Operationdiv extends Operation {
Public Function GetValue ($num 1, $num 2) {
try {
if ($num 2==0) {
throw new Exception ("divisor cannot be 0");
}else {
return $num 1/$num 2;
}
}catch (Exception $e) {
echo "error message:". $e->getmessage ();
}
}
}
?>

The object-oriented inheritance feature is used here, first declaring a virtual base class, and specifying a method in the base class that must be implemented (GetValue ())
Analysis: By using object-oriented inheritance, we can easily extend the original program, such as: ' exponentiation ', ' root ', ' logarithmic ', ' trigonometric ', ' statistics ' and so on.
Copy CodeThe code is as follows:
/**
* Seeking remainder class (remainder)
*
*/
Class Operationrem extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1% $num 12;
}
}
?>

We only need to write another class (the class inherits the virtual base class), in the class to complete the corresponding functions (such as: exponentiation), and greatly reduce the coupling degree, convenient for future maintenance and expansion
Now there is one more question unresolved, that is, how can the program instantiate the corresponding object according to the user input operator?
Workaround: Use a separate class to implement the instantiation process, which is the factory
The code is as follows:
Copy CodeThe code is as follows:
/**
* Engineering class, mainly used to create objects
* Function: According to the input operation symbol, the factory can instantiate the suitable object
*
*/
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 articles, reproduced please specify the source: http://www.cnblogs.com/hongfei/

http://www.bkjia.com/PHPjc/325885.html www.bkjia.com true http://www.bkjia.com/PHPjc/325885.html techarticle Simple Factory mode: ① Abstract base class: class defines abstract methods to implement ② in subclasses that inherit from the subclass of the abstract base class: Implementing an abstract method in a base class ③ factory class: Use ...

  • 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.