(ii) design mode of PHP Project application (Simple Factory mode: Calculator)

Source: Internet
Author: User

1 Introduction to Simple Factory mode

The essence of the simple factory model is that a factory class dynamically determines which product class (these product classes inherit from a parent class or interface) should be created, based on the parameters passed in.


2 Pattern Composition 1) factory (Creator) role
The core of the simple factory pattern, which is responsible for implementing the internal logic of creating all instances. The method of creating a product class for a factory class can be called directly by the outside world to create the desired product object.

2) Abstract Product role
The parent class of all objects created by the simple factory pattern, which is responsible for describing the common interfaces common to all instances.

3) Specific products (concrete product) role
is the creation target of the simple factory pattern, and all created objects are instances of a specific class that acts as the role.

3 Mode core idea the core idea of a simple factory model is to create an instantiated process with a single factory class.

4 schema Diagram


Create a simple factory class, and a simple factory class to create an instance of a specific product.


5 Project Application 5.1 Requirements Description

Implement a computer console program that requires the input of two numbers and a budget symbol to get the results. ("Big Talk design Mode")


5.2 Demand Analysis

According to the requirements, the operation can be designed as an abstract class, addition operations, subtraction operations, multiplication operations, division operations are inherited from this abstract class. Then design a factory class to create a concrete instance.


5.3 Design Architecture Diagram

5.4 Program source code download

http://download.csdn.net/detail/clevercode/8695611


5.5 Program description in operation.php and simplefactorypattern.php.

1) Abstract Product role: Operation abstract class (operation).

Operation Abstract class operation{        //Digital a    protected $_numbera = null;        Number b    protected $_numberb = null;    /**     * Set member a     *     * @param double $num number     * @return void     *    /Public Function Setnumbera ($num) {        $this->_numbera = $num;    }    /**     * Get member a     *     * @return Double number     *    /Public Function Getnumbera () {        return $this->_ Numbera;    }    /**     * Set member B     *     * @param double $num number     * @return void     *    /Public Function Setnumberb ($num) {        $this->_numberb = $num;    }    /**     * Get member B     *     * @return Double number     *    /Public Function Getnumberb () {        return $this->_ Numbera;    }    /**     * Get operation result     *     * @return double digit     *    /Public Function GetResult () {        return null;    }}

2) Specific products (concrete product) Roles: addition Operations (OPERATIONADD), subtraction Operations (operationsub), multiplication (Operationmul), Division Operations (OPERATIONDIV).

Addition class Operationadd extends operation{    /**     * Get operation result     *     * @return Double number    */Public function GetResult () {        return $this->_numbera + $this->_numberb;    }} Subtraction class Operationsub extends operation{    /**     * Get operation result     *     * @return Double number    */Public function GetResult () {        return $this->_numbera-$this->_numberb;    }} Multiplication Classes Class Operationmul extends operation{    /**     * Get operation result     *     * @return Double number    */Public function GetResult () {        return $this->_numbera * $this->_numberb;    }} Division classes Class Operationdiv extends operation{    /**     * Get operation result     *     * @return Double number    */Public function GetResult () {        if ($this->_numberb = = 0) {            return null;        }        return $this->_numbera/$this->_numberb;    }}

3) Factory (Creator) Role: Factory Class (Operationfactory).

<?php/** * simplefactorypattern.php * * Design mode: Simple Factory mode * * Mode introduction: Use a separate class to create the instantiation process, called the Simple Factory. Benefits in the future increase or decrease * Instances only need to modify the factory. * Special statement: The source code is based on the "Big Talk Design Model" in the Book of C # to change into PHP code, and the book * Code will be changed and optimized. * * Copyright (c) http://blog.csdn.net/CleverCode * * Modification History: *--------------------* 2015/5/5, by Cle Vercode, create * *///load all instance classes include_once (' operation.php ');//create a project to produce an instance class operationfactory{/** * Based on the operation of different real        Examples of different objects * * @return object returns the instantiated objects */public static function Createoperate ($operate) {$oper = null; Switch ($operate) {//Instance addition class case ' + ': $oper = new Operationadd ()                ;                        Break                Instance subtraction class case '-': $oper = new Operationsub ();                        Break                Instance multiplication class case ' * ': $oper = new Operationmul ();                        Break Instance multiplication class case '/': $oper = New Operationdiv ();                        Break        Default: $oper = null;    } return $oper; }}//Client Class client{/** * Main functions */Public Function main () {//factory Create instance $operObject = Operationfa                Ctory::createoperate (' + ');        if ($operObject = = null) {return ' $operate not found ';                }//Set number a $operObject->setnumbera (5);                Set the number B $operObject->setnumberb (2);    Arithmetic echo $operObject->getresult ();    }}//Program Entry function start () {//Call client main function $client = new client (); $client->main ();} Start ();? >

6 Summary 1) Advantages:
The factory class is the key to the whole pattern. Contains the necessary logical judgments, based on the information given by the outside world, to determine exactly what specific class of objects should be created. By using the factory class, outsiders can get rid of the embarrassing situation of directly creating specific product objects, just need to be responsible for "consumption" object. Without having to worry about how these objects are created and how they are organized. The respective responsibilities and rights are clarified, which facilitates the optimization of the whole software architecture. There is no need to know how the instance works, just create it in the factory.


2) Disadvantages:
Because the factory class centralizes all instances of the creation logic, violates the cohesion responsibility allocation principle, the whole creation logic is concentrated in a factory class, it can create the class can only be considered beforehand, if you need to add new classes, you need to change the factory class.
As the number of specific product classes in the system increases, there may be a need for factory classes to create different instances based on different conditions. This kind of judgment of the condition and the judgment of the specific product type staggered together, it is difficult to avoid the spread of the module function, the maintenance and expansion of the system is very unfavorable;

You need to modify the factory whenever you need to add or delete instances. However, once the factory is out of the question, all instances cannot be used.


Copyright Notice:

1) original works, from "Clevercode's blog" , please be sure to mention the following original address when reproduced , otherwise hold the copyright legal responsibility.

2) Original address : http://blog.csdn.net/clevercode/article/details/45692995 ( reprint must indicate this address ).

3) welcome everyone to pay attention to my blog more wonderful content: Http://blog.csdn.net/CleverCode.


(ii) design mode of PHP Project application (Simple Factory mode: Calculator)

Related Article

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.