PHP Factory mode

Source: Internet
Author: User

PHP Factory mode

The main focus is the simple engineering model. Scenario: Write a simple calculator common notation: <?php class calculate{function GetResult ($inputA, $inputB, $symbol) {switch ($symbol) {Case "+":$result = $inputA + $inputB;Break ;Case "-";$result = $inputA-$inputB;Break ;Default:$result = "";Break ;}}}//Client code $calculate =new Calculate (), $calculate->getresult (1, 2, "+"); There is nothing wrong with the above example.  But one day the need to change, ask this calculator can calculate multiplication, division, directly add Swtich branch can solve, suddenly one day demand in change, seek root, more complex arithmetic of time?  Factory mode According to my understanding, is to provide a set of classes, such as addition into the addition of the class operation, subtraction into the subtraction class operation. Simple Engineering Mode implementation: Abstract class symbol{Abstract function GetResult ();}//addition class Jiafa extend symbol{function getresult{//addition Operation}}//Subtraction class Jianfa extend symbol{function getresult{//Subtraction Operations}}//multiplication Classes Class Chengfa extend symbol{function getresult{//multiplication Operation}}//Factory classes Class factory{function Calculate ($params) {switch ($params) {Case "+":$operate =new Jiafa ();$operate->getresult;Break ;Case "-":$operate =new Jianfa ();$operate->getresult;Break ;... ..}}From the above code, although the factory still has a switch branch, but the more complex things to the addition class to complete, rather than focus on the implementation process.

PHP Factory mode

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.