Examples of simple factory patterns in PHP

Source: Internet
Author: User
Tags class definition extend getmessage inheritance

Simple Factory mode:
① abstract base class: class definition abstract Some methods to implement in subclasses
② inherits from the abstract base class: Implementing an abstract method in a base class
③ Factory class: Used to instantiate objects

Read the article and look back at this picture, the effect will be better

Adopt Package method

The code is as follows Copy Code
<?php
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 incorrectly:". $e->getmessage ();
}
}
}
$test =new Calc ();
echo $test->calculate (2,3, ' + ');//Print: 5
echo $test->calculate (5,0, '/');//print: You entered incorrectly: divisor cannot be 0
?>

Advantages: The above code uses the Object-oriented encapsulation feature, as long as the Include this class, other pages can be used casually

Disadvantages: Inability to extend and maintain flexibility
For example, to add a "remainder" operation, you need to include a branch statement in the switch statement block, and the code needs to make the following changes
Add a spoke statement

The code is as follows Copy Code
<?php
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 incorrectly:". $e->getmessage ();
}
}
}
?>

Code Analysis: Using the above method to add a new functional operation 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 wrong
② If you want to add a lot of functionality, for example: ' 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, a function of computing function if there are twenty or thirty case branch statements, the code will be more than one screen, not only the readability of the code is greatly reduced, the key is, in order to add small functionality, but also to allow the rest of the irrelevant to participate in the interpretation, which makes the implementation of the program efficiency
Solution: Using Oop's inheritance and polymorphic thinking
Preliminary realization of simple factory model

The code is as follows Copy Code
<?php
/**
* Operation class
* Class must be declared abstract because it contains abstract methods
*/
Abstract class operation{
An abstract method cannot contain a function body
Abstract public Function GetValue ($num 1, $num 2);//strongly require subclasses to implement this 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 attribute is used, first declaring a virtual base class, specifying the method that subclasses must implement in the base class (GetValue ())

Analysis: By adopting the Object-oriented inheritance feature, we can easily extend the original program, such as: ' Powers ', ' square ', ' logarithm ', ' trigonometric ', ' statistics ' and so on.

Remainder class

The code is as follows Copy Code

<?php
/**
* Remainder category (remainder)
*
*/
Class Operationrem extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1% $num 12;
}
}
?>

We only need to write a separate class (this class inherits the virtual base class), completes the corresponding function in the class (for example: the computation of the exponentiation), and greatly reduces the coupling degree, facilitates the future maintenance and the extension

There is still a problem unresolved, that is, how to get the program to instantiate the corresponding object based on the operator entered by the user?
Workaround: Use a separate class to implement the instantiation process, this class is the factory
The code is as follows:

Factory class

The code is as follows Copy Code

<?php
/**
* Engineering class, mainly used to create objects
* Function: According to the input operation symbol, the factory can instantiate the appropriate 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;
?>

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.